情况:我正在写一个张量流程序。我试图创建一个损失函数来比较克矩阵。计算克数矩阵似乎进展顺利 - 或者至少程序没有崩溃。然而,在我计算克数矩阵后,我想做元素减法,元素方形平方,然后总结所有元素。当我尝试进行元素减法时,程序似乎崩溃了。这是(我认为)相关的代码:
def _gram_matrix(self, F, N, M):
print("in gram")
F = np.reshape(F,(M,N))
F_trans = np.transpose(F)
return np.dot(F,F_trans)
def _single_style_loss(self, a, g):
print("in single style loss")
print("a shape ",a.shape)
N = a.shape[3]
M = a.shape[1]*a.shape[2]
gram_a = self._gram_matrix(a,N,M)
gram_g = self._gram_matrix(g,N,M)
print("out of gram")
multiplier = 1/(4*N*N*M*M)
print("leaving single style loss")
return_val = np.subtract(gram_a,gram_g)
print("subtract was fine")
return_val = np.square(return_val)
print("square was fine")
array_sum = np.sum(return_val)
print("sum was fine")
array_sum = multiplier*array_sum
print("multiplier was fine")
print("going to return ",array_sum)
return array_sum
def _style_loss(self, A):
print("in style loss")
loss = 0;
with tf.Session() as sess:
sess.run(self.input_img.assign(self.initial_img))
generated_layers = sess.run([getattr(self.vgg,layer) for layer in self.style_layers])
sess.run(self.input_img.assign(self.style_img))#reset input_img to style img
for i in range(len(self.style_layer_w)):
print("len ",self.style_layer_w)
print("len generated layers",len(generated_layers))
print("len style layers",len(A))
loss += self.style_layer_w[i]*self._single_style_loss(A[i],generated_layers[i])
print("loss ",loss)
self.style_loss = loss
print("out of style loss")
所以我得到的错误是:"留下单一风格的损失 被杀:9"这就是为什么我总结下一行(np.subtract行)是问题。可悲的是,我不知道为什么这条线是一个问题,我会非常感谢任何人提供的洞察力。谢谢!