【问题标题】:WARNING:tensorflow:Layer my_model is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2WARNING:tensorflow:Layer my_model 将输入张量从 dtype float64 转换为 layer 的 float32 dtype,这是 TensorFlow 2 中的新行为
【发布时间】:2020-12-01 01:21:52
【问题描述】:

在我的 Tensorflow 神经网络开始训练之前,会打印出以下警告:

WARNING:tensorflow:Layer my_model 正在从 dtype float64 到该层的 float32 dtype,这是新行为 在 TensorFlow 2 中。该层具有 dtype float32 因为它是 dtype 默认为浮点数。如果你打算在 float32 中运行这个层,你 可以放心地忽略此警告。

如有疑问,可能会出现此警告 仅当您将 TensorFlow 1.X 模型移植到 TensorFlow 时才会出现问题 2. 要将所有层更改为默认dtype float64,请致电tf.keras.backend.set_floatx('float64')

只改变这一层, 将 dtype='float64' 传递给层构造函数。如果你是作者 在这一层,您可以通过传递 autocast=False 来禁用自动投射 到基础层构造函数。

现在,根据错误消息,我可以通过将后端设置为 'float64' 来消除此错误消息。但是,我想深入了解并手动设置正确的dtypes

完整代码:

import tensorflow as tf
from tensorflow.keras.layers import Dense, Concatenate
from tensorflow.keras import Model
from sklearn.datasets import load_iris
iris, target = load_iris(return_X_y=True)

X = iris[:, :3]
y = iris[:, 3]

ds = tf.data.Dataset.from_tensor_slices((X, y)).shuffle(25).batch(8)

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.d0 = Dense(16, activation='relu')
    self.d1 = Dense(32, activation='relu')
    self.d2 = Dense(1, activation='linear')

  def call(self, x):
    x = self.d0(x)
    x = self.d1(x)
    x = self.d2(x)
    return x

model = MyModel()

loss_object = tf.keras.losses.MeanSquaredError()

optimizer = tf.keras.optimizers.Adam(learning_rate=5e-4)

loss = tf.keras.metrics.Mean(name='loss')
error = tf.keras.metrics.MeanSquaredError()

@tf.function
def train_step(inputs, targets):
    with tf.GradientTape() as tape:
        predictions = model(inputs)
        run_loss = loss_object(targets, predictions)
    gradients = tape.gradient(run_loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    loss(run_loss)
    error(predictions, targets)

for epoch in range(10):
  for data, labels in ds:
    train_step(data, labels)

  template = 'Epoch {:>2}, Loss: {:>7.4f}, MSE: {:>6.2f}'
  print(template.format(epoch+1,
                        loss.result(),
                        error.result()*100))
  # Reset the metrics for the next epoch
  loss.reset_states()
  error.reset_states()

【问题讨论】:

  • this 问题的建议可能会对您有所帮助。
  • 我看到这与 cmets 不太清楚有关,也没有发布答案。随意根据我提供的代码提供答案。

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

tl;dr 为避免这种情况,请将您的输入发送到 float32

X = tf.cast(iris[:, :3], tf.float32) 
y = tf.cast(iris[:, 3], tf.float32)

numpy:

X = np.array(iris[:, :3], dtype=np.float32)
y = np.array(iris[:, 3], dtype=np.float32)

说明

默认情况下,Tensorflow 使用floatx,默认为float32,这是深度学习的标准。您可以验证这一点:

import tensorflow as tf
tf.keras.backend.floatx()
Out[3]: 'float32'

您提供的输入(鸢尾花数据集)是 dtype float64,因此 Tensorflow 的权重默认 dtype 与输入不匹配。 Tensorflow 不喜欢这样,因为强制转换(更改 dtype)成本很高。 Tensorflow 在处理不同 dtype 的张量时通常会抛出错误(例如,比较 float32 logits 和 float64 标签)。

它所说的“新行为”:

层 my_model_1 将输入张量从 dtype float64 转换为该层的 dtype float32,这是 TensorFlow 2 中的新行为

它是否会自动将输入dtype转换为float32。 Tensorflow 1.X 在这种情况下可能会抛出异常,尽管我不能说我曾经使用过它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2019-04-28
    • 1970-01-01
    • 2016-06-14
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多