关于keras模型的困惑:__call__ vs.call vs.predict方法 [英] Confusion about keras Model: __call__ vs. call vs. predict methods
问题描述
我意识到我不太了解调用Keras模型的__call__
,call
或predict
方法之间的区别.
I have realized that I do not quite understand the difference between calling either the __call__
, call
, or predict
method of a Keras' model.
例如,我们有一个训练有素的keras模型.调用代码后:
For example, we have a trained keras model. After calling the code:
# After training.
y_pred_1 = model(X_new)
y_pred_2 = model.call(X_new)
y_pred_3 = model.predict(X_new)
我希望y_pred_1
,y_pred_2
和y_pred_3
都相同.
但是事实证明它们并不相同.
I expected that y_pred_1
, y_pred_2
, and y_pred_3
are all the same.
But it turned out that they are not the same.
您能告诉我区别吗?
推荐答案
我的糟糕,这是我的代码中的错误.
My bad, it was a mistake in my code.
事实证明,这三种方法之间没有本质区别.
It turned out that there is no essential difference between these three methods.
唯一的区别是call
仅接受张量,而其他两种方法也接受NumPy数组.
The only difference is that call
accepts only tensors, while the other two methods also accept NumPy arrays.
这是一个玩具代码,显示三种方法相同:
Here is a toy code showing that three methods are the same:
import numpy as np
import tensorflow as tf
model = tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=(2, )),
tf.keras.layers.Dense(2),
]
)
model.compile(loss='mse')
W = model.trainable_variables[0]
W.assign(np.array([[1.0, 0.0], [0.0, 1.0]]).T)
input = np.array([[1.0, 2.0], [3.0, 4.0], ], dtype=np.float32)
print("__call__:")
print(model(input))
print("Call:")
print(model.call(tf.convert_to_tensor(input)))
print("Predict:")
print(model.predict(input))
这篇关于关于keras模型的困惑:__call__ vs.call vs.predict方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!