回答

2

與通常一樣,你需要向量化它的損失,而不是用列工作:

loss = X - tf.matmul(X, C) 
loss = tf.reduce_sum(tf.square(loss)) 

reg_loss = tf.reduce_sum(tf.square(C), 0) # L2 loss for each column 
reg_loss = tf.reduce_sum(tf.sqrt(reg_loss)) 

total_loss = loss + lambd * reg_loss 

爲了在C的對角線上實現零約束,最好的方法是用另一個常數將其添加到損失中lambd2

reg_loss2 = tf.trace(tf.square(C)) 
total_loss = total_loss + lambd2 * reg_loss2 
+0

非常感謝!我正在考慮使用tf.slice()來獲得矩陣的一列,你認爲這樣做會有效嗎? tf.slice()的機制是什麼? – xxx222

+0

這也將工作,因爲梯度會反向傳播到原始變量C(和X),但它會非常低效 –

+0

明白了,非常感謝。 – xxx222