【发布时间】:2019-08-11 19:03:50
【问题描述】:
我正在尝试使用神经网络进行 SVD。我的输入是一个矩阵(假设只有 4x4 矩阵),输出是一个表示分解形式的向量(假设输入是 4x4,这将是一个 36 个元素的向量,其中 U 有 16 个元素,S 有 4 个元素,还有 16 个元素对于 V.T)。
我正在尝试定义一个自定义损失函数,而不是在分解形式上使用 MSE 之类的东西。因此,我不想比较 36 个长度向量的损失,而是计算重建矩阵之间的损失。所以如果A = U * S * V.T(实际)和A' = U' * S' * V.T'(预测),我想计算A和A'之间的损失。
我对 tensorflow 和 keras 还很陌生,所以我可能会做一些幼稚的事情,但这是我目前所拥有的。虽然逻辑对我来说似乎没问题,但我收到了 TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn. 我不知道为什么会这样以及如何解决它?另外,我是否需要像我目前所做的那样将reconstruct_matrix 的输出展平,还是应该保持原样?
# This function takes the decomposed matrix (vector of U, S, V.T)
# and reconstructs the original matrix
def reconstruct_matrix(decomposed_vector):
example = decomposed_vector
s = np.zeros((4,4))
for en, i in enumerate(example[16:20]):
s[en, en] = i
u = example[:16].reshape(4,4)
vt = example[20:].reshape(4,4)
orig = np.matmul(u, s)
orig = np.matmul(orig, vt)
return orig.flatten() # Given that matrices are 4x4, this will be a length 16 vector
# Custom loss that essentially computes MSE on reconstructed matrices
def custom_loss(y_true, y_pred):
Y = reconstruct_matrix(y_true)
Y_prime = reconstruct_matrix(y_pred)
return K.mean(K.square(Y - Y_prime))
model.compile(optimizer='adam',
loss=custom_loss)
注意:我的keras版本是2.2.4,我的tensorflow版本是1.14.0。
【问题讨论】:
-
张量流版本?在发布问题时始终指定它,因为即使是次要版本,此框架也在改变范式。
-
好点!我的keras版本是2.2.4,我的tensorflow版本是1.14.0。
标签: python tensorflow keras loss-function svd