Tensorflow 张量流中未知维数的处理

Tensorflow 张量流中未知维数的处理,tensorflow,deep-learning,Tensorflow,Deep Learning,我编写了一个函数,用于计算形状(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)]) gr

我编写了一个函数,用于计算形状(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
要测试我对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_神经元)”)

调试时,我发现model.extract_features()[5]的形状是(?,,128),因此无法进行分割

style\u img\u test的维度是((1,192,242,3)),因此当我们运行会话时,H,W,C将被填充


你能指导我如何解决这个问题吗?

我做了以下更改,效果很好

def calc_gram_矩阵(特征,normalize=True):
#输入:特征是形状的张量(1,高度,宽度,通道)
特征形状=tf.形状(特征)
H=特征与形状[1]
W=特征与形状[2]
C=特征和形状[3]
矩阵=tf.重塑(特征,形状=[-1,C])
gram=tf.matmul(tf.transpose(矩阵),矩阵)
如果正常化:
tot_神经元=H*W*C
tot_神经元=tf.cast(tot_神经元,tf.32)
gram=tf.divide(gram,tot_神经元)
返回克

我做了以下更改,它成功了

def calc_gram_矩阵(特征,normalize=True):
#输入:特征是形状的张量(1,高度,宽度,通道)
特征形状=tf.形状(特征)
H=特征与形状[1]
W=特征与形状[2]
C=特征和形状[3]
矩阵=tf.重塑(特征,形状=[-1,C])
gram=tf.matmul(tf.transpose(矩阵),矩阵)
如果正常化:
tot_神经元=H*W*C
tot_神经元=tf.cast(tot_神经元,tf.32)
gram=tf.divide(gram,tot_神经元)
返回克

使用
tf.shape
获得一个整数张量形状(您还需要删除
int()
cast)。即使图形构造过程中形状未知(这是
tensor.shape
提供给您的信息),此功能仍然有效。谢谢@AllenLavoie,成功了!:)非常感谢@AllenLavoie:)使用
tf.shape
获得一个作为整数张量的形状(您还需要删除
int()
cast)。即使图形构造过程中形状未知(这是
tensor.shape
提供给您的信息),此功能仍然有效。谢谢@AllenLavoie,成功了!:)非常感谢@AllenLavoie:)