在 Tensorflow 2.3.1 中读取损失函数的值

Posted

技术标签:

【中文标题】在 Tensorflow 2.3.1 中读取损失函数的值【英文标题】:Read values of the loss function in Tensorflow 2.3.1 【发布时间】:2021-02-25 15:39:07 【问题描述】:

我的目标是制作个人损失函数,为此我想访问通过参数接收到的值。目标是在某个 np 数组中的 y_true 中接收这些值,对其进行一些修改,然后实际操作损失函数。我尝试使用 Tensor.numpy() 将数据从 Tensor 转换为 np.array,但结果是: p>

AttributeError: 'Tensor' 对象没有属性 'numpy'

确实,这个错误似乎与我的变量y_true不是EagerTensor,而只是Tensor有关。由于我正在尝试个性化我的层和模型创建,我不知道如何启用急切执行模式。这是我正在编写的代码:

import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
import numpy as np

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 28 * 28).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28 * 28).astype("float32") / 255.0


class Dense(layers.Layer):
    def __init__(self, units):
        super(Dense, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.w = self.add_weight(
            name="w",
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            trainable=True, # We can define whether a variable will be trained in the backpropagation 
                            # Process or not, by changing the field 'trainable'. 
        )
        self.b = self.add_weight(
            name="b", shape=(self.units,), initializer="random_normal", trainable=True,
        )

    def call(self, inputs):
        return tf.matmul(inputs, self.w) + self.b # Defining the operation of the layer, i.e. the forward
                                                  # propagation methodology


class MyReLU(layers.Layer):
    def __init__(self):
        super(MyReLU, self).__init__()

    def call(self, x):
        return tf.math.maximum(x, 0)


class MyModel(keras.Model):  # model.fit, model.evalute, model.predict
    def __init__(self, num_classes=10):
        super(MyModel, self).__init__()
        self.dense1 = Dense(64)
        self.dense2 = Dense(num_classes)
        self.relu = MyReLU()

    def call(self, x):
        x = self.dense1(x) # Creating the first layer and initializing it

        x = self.relu(x)   # Genereting the output of the first layer through a personalized
                           # ReLu activation function

        x = self.dense2(x) # This output is passed as input to the next (and in this case final) layer

        return x

def Personalized_loss_procedure(y_true, y_pred):

    array = y_true.numpy()

    y_true = tf.cast(y_true, tf.float32)
    subtrac = tf.subtract(y_true, y_pred)
    powl = tf.pow(subtrac, tf.constant(2.0, dtype=tf.float32))
    divide = tf.reduce_sum(powl)
    sqrt = tf.divide(divide, tf.cast(tf.size(y_true), tf.float32))
    return tf.sqrt(sqrt)

model = MyModel()
model.compile(
    loss=Personalized_loss_procedure,
    optimizer=keras.optimizers.Adam(),
    metrics=["accuracy"],
)
 
model.fit(x_train, y_train, batch_size=32, epochs=2, verbose=2)
model.evaluate(x_test, y_test, batch_size=32, verbose=2)

在这种情况下,如何将 Tensor 转换为 Numpy?在这种情况下,有没有办法将 Tensor 转换为 EagerTensor? 我正在使用 Tensorflow 2.3.1,但退回到旧版本的 tf2 不会有问题。 在发布的代码中,感兴趣的一行是 def Personalized_loss_procedure 语句的右下方。

【问题讨论】:

【参考方案1】:

你不能在损失函数中使用 numpy,因为 tensorflow 将无法传播错误。

【讨论】:

以上是关于在 Tensorflow 2.3.1 中读取损失函数的值的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Tensorflow Estimator 的每个全局步骤中获取训练损失并评估损失?

报告训练数据集中特定样本的训练损失,而不是训练过程中的平均损失 (TensorFlow)

Tensorflow:损失变成'NaN'

使用预训练 vgg19 tensorflow,Keras 在 CNN 自动编码器中定义自定义损失(感知损失)

TensorFlow 多个损失值

TensorFlow中如何选择交叉熵损失?