【发布时间】:2020-03-29 20:36:19
【问题描述】:
我正在尝试实现自定义度量函数以及自定义损失函数。两种实现都面临同样的问题,所以我将把这篇文章的重点放在其中一个上。
我的目标是在 fit 方法期间访问张量的值,以便根据存储在 y_true 和 y_pred 中的所述值进行计算。 这些计算无法使用内置的 Keras 后端函数完成。
例如,我们有下面的虚拟代码:
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Input, LSTM, Dense
from tensorflow.keras.metrics import Metric
x, y = list(), list()
for _ in range(10):
x.append(np.arange(10))
y.append(np.random.randint(0, 2))
x = np.reshape(x, (len(x), 1, len(x[0])))
y = np.asarray(y)
class custom_metric(Metric):
def __init__(self, name = 'custom_metrics', **kwargs):
super(custom_metric, self).__init__(name = name, **kwargs)
self.true_positives = self.add_weight(name = 'tp', initializer = 'zeros')
def update_state(self, y_true, y_pred, sample_weight = None):
self.test(y_true, y_pred)
# In a real application, new_metric would be a function that depends on
# the values stored in both y_true and y_pred
new_metric = 0.1
self.true_positives.assign_add(tf.reduce_sum(new_metric))
def result(self):
return self.true_positives
def reset_states(self):
self.true_positives.assign(0.)
def test(self, y_true, y_pred):
tf.print(y_true)
print(y_true.numpy())
model = Sequential([
LSTM(5,
input_shape = (np.asarray(x).shape[1], np.asarray(x).shape[2]),
return_sequences = True,
recurrent_initializer = 'glorot_uniform',
activation = 'tanh',
recurrent_dropout = 0.2,
dropout = 0.2
),
Dense(2, activation = 'softmax')
])
model.compile(
optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy', custom_metric()]
)
model.fit(
x, y,
epochs = 1,
batch_size = 1
)
我写了这个虚拟函数test 只是为了说明这个问题。如果仅使用 tf.print,则代码运行,并且在拟合完成后张量中的值将打印在 stdout 上。但是,我是否尝试y_true.numpy 或print(y_true.numpy()) 之类的代码返回
AttributeError: 'Tensor' object has no attribute 'numpy'
我从多个 StackOverflow 和 Github 线程中尝试了几种方法,包括 sess = tf.Session() 与 .eval()、tf.GradientTape 的组合,但不知何故未能成功实现其中任何一个。
有人知道如何解决这个问题吗?
【问题讨论】:
标签: tensorflow keras tensorflow2.0 tf.keras