【发布时间】:2020-04-18 21:59:32
【问题描述】:
我正在尝试在 TensorFlow 2 上进行歌手分类。但是,当我训练我的模型时,我发现所有权重最终都变成了零矩阵。我不确定为什么会出现这个问题。请告诉我。
以下代码是我的问题的最简单版本。我在TF2.1、TF2.2rc0、TF2.2rc3上测试了这段代码,结果都一样。
import tensorflow as tf
import numpy as np
audios = tf.keras.layers.Input(
shape= [None,],
dtype= tf.float32
)
singers = tf.keras.layers.Input(
shape= [],
dtype= tf.int32
)
new_Tensor = tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis= -1))(audios) #[Batch, T, 1]
new_Tensor = tf.keras.layers.Dense(128)(new_Tensor) #[Batch, T, 128]
new_Tensor = tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis= 1))(new_Tensor) #[Batch, 128]
new_Tensor = tf.keras.layers.Dense(12)(new_Tensor) #[Batch, 12]
optimizer = tf.keras.optimizers.Adam(
learning_rate= 0.002
)
model = tf.keras.Model(
inputs= audios,
outputs= new_Tensor
)
model.summary()
while True:
with tf.GradientTape() as tape:
# audios = np.random.rand(3, 16000) * 2 - 1
singers = np.random.randint(0, 12, 3)
audios = np.zeros((3, 16000)) + np.expand_dims(singers, axis= -1)
logits = model(audios, training= True)
loss = tf.reduce_sum(tf.keras.losses.sparse_categorical_crossentropy(
y_true= singers,
y_pred= logits
))
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients([
(gradient, variable)
for gradient, variable in zip(gradients, model.trainable_variables)
])
print(loss)
for gradient, variable in zip(gradients, model.trainable_variables):
print('{}: {}'.format(variable.name, gradient))
编辑:
我找到了答案。 'tf.keras.losses' 在没有编译的情况下不起作用。当我将它们更改为“tf.nn.sparse_softmax_cross_entropy_with_logits”时,它现在可以工作了。
【问题讨论】:
标签: tensorflow2.0