[英]Tensorflow: How to index one tensor using another tensor with unknown dimensions?
[英]Dealing with unknown dimensions in Tensorflow
我編寫了一個函數,用於計算形狀為(1,H,W,C)的圖像特征的gram矩陣。 我寫的方法如下:
def calc_gram_matrix(features, normalize=True):
#input: features is a tensor of shape (1, Height, Width, Channels)
_, H, W, C = features.shape
matrix = tf.reshape(features, shape=[-1, int(C)])
gram = tf.matmul(tf.transpose(matrix), matrix)
if normalize:
tot_neurons = H * W * C
gram = tf.divide(gram,tot_neurons)
return gram
要測試我對語法矩陣的實現,有一種方法:
def gram_matrix_test(correct):
gram = calc_gram_matrix(model.extract_features()[5]) #
student_output = sess.run(gram, {model.image: style_img_test})
print(style_img_test.shape)
error = rel_error(correct, student_output)
print('Maximum error is {:.3f}'.format(error))
gram_matrix_test(answers['gm_out'])
當我運行gram_matrix_test()時,出現錯誤-> ValueError:無法將未知尺寸轉換為張量:?
(錯誤在此行上->“ gram = tf.divide(gram,tot_neurons) ”)
在調試時,我發現model.extract_features()[5]的形狀為(?,?,?,128),因此無法進行除法。
style_img_test的維度為((( 1,192,242,3 ))),因此當我們運行會話H,W,C時將被填充。
您能指導我如何解決此問題嗎?
我進行了以下更改,並且有效。
def calc_gram_matrix(features, normalize=True):
#input: features is a tensor of shape (1, Height, Width, Channels)
features_shape = tf.shape(features)
H = features_shape[1]
W = features_shape[2]
C = features_shape[3]
matrix = tf.reshape(features, shape=[-1, C])
gram = tf.matmul(tf.transpose(matrix), matrix)
if normalize:
tot_neurons = H * W * C
tot_neurons = tf.cast(tot_neurons, tf.float32)
gram = tf.divide(gram,tot_neurons)
return gram
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.