Tensorflow 2.3: AttributeError: ‘Tensor’ object has no attribute ‘numpy’

使用tf.py_function()来重构一下函数

def masked_sparse_categorical_crossentropy(y_true, y_pred):
    """ :param y_true: (batch_size, seq_len, 2) dtype=float32 contains word index and word mask :param y_pred: (batch_size, seq_len, vocab_size) dtype=float32 :param sample_weight: default None, why use this ? compatible to the standard loss :return: Penalized loss """
    y_true_val = y_true  # [:, :, 0]
    np.set_printoptions(suppress=True)
    def pr(x, y):
        print(np.max(x.numpy(), axis=-1))
        print(np.argmax(x.numpy(), axis=-1))
        print(y.numpy())
        with open(r'/6T_data/anli/result_neg', 'a', encoding='utf-8') as f:
            f.write(str(np.max(x.numpy())))
        return x, y
    # print(y_pred.numpy())
    tf.py_function(pr, [y_pred, y_true], [tf.float32, tf.int32])
    # get mask info
    padding_mask = tf.cast(tf.not_equal(y_true_val, 0), dtype=tf.float32)

参考:https://stackoverflow.com/questions/63557955/tensorflow-2-3-attributeerror-tensor-object-has-no-attribute-numpy

本文地址:https://blog.csdn.net/andy123564/article/details/110878970