Tensorflow 1.x 到 Tensorflow 2.1.0
Tensorflow 1.x to Tensorflow 2.1.0
我正在尝试将使用 Tensorflow 1.x 编写的代码更新为使用 Tensorflow 2.1.0 编写的代码。我一直在使用 Tensorflow 2.1.0 文档转换代码,直到这段代码我才遇到问题。
loss = tf.losses.softmax_cross_entropy(one_hot_labels, logits)
以上代码是 Tensorflow 1.x 版本,我认为,根据 Tensorflow 2.1.0 文档,正确更新的代码是
loss = tf.nn.softmax_cross_entropy_with_logits(one_hot_labels, logits)
然后,当我运行
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
我收到以下错误。
Loss must be scalar, given: Tensor("softmax_cross_entropy_with_logits/Reshape_2:0", shape=(512,), dtype=float32)**
所以,我猜测在 Tensorflow 1.x 版本中,损失被传递为 'tensor' 到 tf.estimator.EstimatorSpec,但在 Tensorflow 2.1.0 中,损失必须传递为scalar
到 tf.estimator.EstimatorSpec
?如果我没记错的话,Tensorflow 1.x 和 2.1.0 中的损失(此处定义的方式)都是张量。
那么,有谁知道如何将张量转换为标量(我认为这在构建 CNN 模型时既不充分也不有效)或者更好的是,如何解决这个难题?
还是我把原代码转换错了?
如果是 compat.v1,我将不胜感激。除非绝对必要,否则不使用(即除了 compat.v1 之外,没有其他方法可以使用 Tensorflow 2.1.0 中的代码。)
您可以对结果进行平均(tf.losses.softmax_cross_entropy
通过 tf.losses.compute_weighted_loss
所做的):
loss = tf.math.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(one_hot_labels, logits))
我正在尝试将使用 Tensorflow 1.x 编写的代码更新为使用 Tensorflow 2.1.0 编写的代码。我一直在使用 Tensorflow 2.1.0 文档转换代码,直到这段代码我才遇到问题。
loss = tf.losses.softmax_cross_entropy(one_hot_labels, logits)
以上代码是 Tensorflow 1.x 版本,我认为,根据 Tensorflow 2.1.0 文档,正确更新的代码是
loss = tf.nn.softmax_cross_entropy_with_logits(one_hot_labels, logits)
然后,当我运行
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
我收到以下错误。
Loss must be scalar, given: Tensor("softmax_cross_entropy_with_logits/Reshape_2:0", shape=(512,), dtype=float32)**
所以,我猜测在 Tensorflow 1.x 版本中,损失被传递为 'tensor' 到 tf.estimator.EstimatorSpec,但在 Tensorflow 2.1.0 中,损失必须传递为scalar
到 tf.estimator.EstimatorSpec
?如果我没记错的话,Tensorflow 1.x 和 2.1.0 中的损失(此处定义的方式)都是张量。
那么,有谁知道如何将张量转换为标量(我认为这在构建 CNN 模型时既不充分也不有效)或者更好的是,如何解决这个难题?
还是我把原代码转换错了?
如果是 compat.v1,我将不胜感激。除非绝对必要,否则不使用(即除了 compat.v1 之外,没有其他方法可以使用 Tensorflow 2.1.0 中的代码。)
您可以对结果进行平均(tf.losses.softmax_cross_entropy
通过 tf.losses.compute_weighted_loss
所做的):
loss = tf.math.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(one_hot_labels, logits))