【问题标题】:Why all weights become zeros in this code?为什么这段代码中的所有权重都为零?
【发布时间】: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


    【解决方案1】:

    这里有几件事:

    1. 鉴于您想要输入模型的形状,输入应该是:

      audios = tf.keras.layers.Input(
          shape= [None, 1],
          dtype= tf.float32
      )
      singers = tf.keras.layers.Input(
          shape= [128],
          dtype= tf.int32
      )
      
    2. 在您的训练循环中,检查要添加的形状是否可广播。

    【讨论】:

    • 感谢您的回答。但是,输入形状没有问题,因为序列的第一层是扩展尺寸,而歌手也是稀疏目标..
    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2017-05-08
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多