我写了一个函数来计算形状(1,H,W,C)的图像特征的克矩阵。我写的方法如下:
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:无法将未知Dimension转换为Tensor:?
(错误在这一行 - >“ gram = tf.divide(gram,tot_neurons)”)
在调试时我发现 model.extract_features()[5] 的形状是(?,?,?,128),因此无法进行除法。
style_img_test 的维度为((1,192,242,3)),因此当我们运行会话H时,将填充W,C。
你能指导我如何解决这个问题吗?
答案 0 :(得分:4)
我进行了以下更改并且有效。
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