2017-04-13 7 views
0

xとyを長さNのベクトルとし、zを関数z = f(x、y)とします。 Tensorflow v1.0.0では、tf.hessians(z、x)とtf.hessians(z、y)はどちらもN行N列を返します。これは私が期待したものです。tf.concat()によって返される変数のヘッセ行列はNoneです。

しかし、xとyをtf.concatを使ってサイズ2 * Nのベクトルpに連結し、tf.hessian(z、p)を実行すると、エラー "ValueError:None values supported"が返されます。

これは、計算グラフx、y - > zとx、y - > pのため、pとzの間に勾配がないためです。この問題を回避するために、まずpを作成してxとyにスライスしますが、コードを大量に変更する必要があります。よりエレガントな方法がありますか?

関連する質問:Slice of a variable returns gradient None

import tensorflow as tf 
import numpy as np 

N = 2 
A = tf.Variable(np.random.rand(N,N).astype(np.float32)) 
B = tf.Variable(np.random.rand(N,N).astype(np.float32)) 

x = tf.Variable(tf.random_normal([N])) 
y = tf.Variable(tf.random_normal([N])) 

#reshape to N by 1 
x_1 = tf.reshape(x,[N,1]) 
y_1 = tf.reshape(y,[N,1]) 

#concat x and y to form a vector with length of 2*N 
p = tf.concat([x,y],axis = 0) 

#define the function 
z = 0.5*tf.matmul(tf.matmul(tf.transpose(x_1), A), x_1) + 0.5*tf.matmul(tf.matmul(tf.transpose(y_1), B), y_1) + 100 

#works , hx and hy are both N by N matrix 
hx = tf.hessians(z,x) 
hy = tf.hessians(z,y) 

#this gives error "ValueError: None values not supported." 
#expecting a matrix of size 2*N by 2*N 
hp = tf.hessians(z,p) 

答えて

1

その定義によってヘッセ行列を計算します。

gxy = tf.gradients(z, [x, y]) 
gp = tf.concat([gxy[0], gxy[1]], axis=0) 
hp = [] 
for i in range(2*N): 
    hp.append(tf.gradients(gp[i], [x, y])) 

tf.gradientsので(DY/DX)の和を計算するので、第二の偏微分を計算するとき、一方はスカラーベクターをスライスした後、勾配を計算しなければなりません。 tf1.0とpython2でテスト済みです。

+0

もpython3.5で動作します。ありがとう! –

関連する問題