2017-07-18 27 views
4

this questionのような問題があります。カスタム損失関数のテンソルを変更

this questionに与えられた回答に基づいて
def depth_loss_func(lr): 
    def loss(actual_depth,pred_depth): 
     actual_shape = actual_depth.get_shape().as_list() 
     dim = np.prod(actual_shape[1:]) 
     actual_vec = K.reshape(actual_depth,[-1,dim]) 
     pred_vec = K.reshape(pred_depth,[-1,dim]) 
     di = K.log(pred_vec)-K.log(actual_vec) 
     di_mean = K.mean(di) 
     sq_mean = K.mean(K.square(di)) 

     return (sq_mean - (lr*di_mean*di_mean)) 
    return loss 

:私はとして与えられたkerasで損失関数を考案しようとしています。しかし、私はエラーを取得しています:

TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' 

具体的に、この文は、バックエンドがTensorFlowで次の出力に

(Pdb) actual_depth.get_shape() 
TensorShape([Dimension(None), Dimension(None), Dimension(None)]) 

を与えます。ご協力いただきありがとうございます。

答えて

1

このようなnp.prod()を呼び出すときに、私は、形状(None, None, None, 9)のテンソルであなたの例外を再現するために管理:

from keras import backend as K 

#create tensor placeholder 
z = K.placeholder(shape=(None, None, None, 9)) 
#obtain its static shape with int_shape from Keras 
actual_shape = K.int_shape(z) 
#obtain product, error fires here... TypeError between None and None 
dim = np.prod(actual_shape[1:]) 

あなたがあなたのactual_shapeをスライスしていても、タイプNoneの2つの要素を掛け合わしようとしているため、この問題が発生しました(1つ以上の要素として、None)。場合によっては、スライス後に1つの非タイプ要素が残っていれば、Noneintの間にTypeErrorを取得することもできます。

answerあなたが言及した、彼らはそれから引用し、それらの状況で何をするかを指定見撮影:

それに基づいて

For the cases where more than 1 dimension are undefined, we can use tf.shape() with tf.reduce_prod() alternatively.

を、我々はK.shape()を使用することにより、Keras APIにこれらの操作を翻訳することができますそれぞれ(docs)とK.prod()docs):また

z = K.placeholder(shape=(None, None, None, 9)) 
#obtain Real shape and calculate dim with prod, no TypeError this time 
dim = K.prod(K.shape(z)[1:]) 
#reshape 
z2 = K.reshape(z, [-1,dim]) 

、一次元のみが定義されていない場合のを使用することを覚えていますバックエンド(docs)で定義されているように、get_shape()ではなく、3230またはそのラッパーK.get_variable_shape(z)を使用します。これがあなたの問題を解決することを願っています。

+0

これがあなたの問題を解決したことをうれしく思います。あなたのコーディングで幸運を祈る。あなたがこの回答を見つけたら、それを上書きすることも検討してください。 – DarkCygnus

+1

ありがとう@GrayCygnus! – shunyo

関連する問題