我想找到一种使用 Keras 的方法predict_on_batch
inside tf.data.Dataset.map()
in TF2.0.
假设我有一个 numpy 数据集
n_data = 10**5
my_data = np.random.random((n_data,10,1))
my_targets = np.random.randint(0,2,(n_data,1))
data = ({'x_input':my_data}, {'target':my_targets})
and a tf.keras
model
x_input = Input((None,1), name = 'x_input')
RNN = SimpleRNN(100, name = 'RNN')(x_input)
dense = Dense(1, name = 'target')(RNN)
my_model = Model(inputs = [x_input], outputs = [dense])
my_model.compile(optimizer='SGD', loss = 'binary_crossentropy')
我可以批量创建一个dataset
with
dataset = tf.data.Dataset.from_tensor_slices(data)
dataset = dataset.batch(10)
prediction_dataset = dataset.map(transform_predictions)
where transform_predictions
是一个用户定义的函数,它从以下位置获取预测predict_on_batch
def transform_predictions(inputs, outputs):
predictions = my_model.predict_on_batch(inputs)
# predictions = do_transformations_here(predictions)
return predictions
这给出了一个错误predict_on_batch
:
AttributeError: 'Tensor' object has no attribute 'numpy'
据我所理解,predict_on_batch
需要一个 numpy 数组,并且它正在从数据集中获取一个张量对象。
似乎一种可能的解决方案是包装predict_on_batch
在`tf.py_function中,尽管我也无法让它工作。
有谁知道如何做到这一点?