您应该将输入转换为np.float32,这是 Keras 的默认 dtype。查一下:
import tensorflow as tf
tf.keras.backend.floatx()
'float32'
如果你在np.float64 中给 Keras 输入,它会抱怨:
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras import Model
from sklearn.datasets import load_iris
iris, target = load_iris(return_X_y=True)
X = iris[:, :3]
y = iris[:, 3]
ds = tf.data.Dataset.from_tensor_slices((X, y)).shuffle(25).batch(8)
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.d0 = Dense(16, activation='relu')
self.d1 = Dense(32, activation='relu')
self.d2 = Dense(1, activation='linear')
def call(self, x):
x = self.d0(x)
x = self.d1(x)
x = self.d2(x)
return x
model = MyModel()
_ = model(X)
警告:tensorflow:Layer my_model 将输入张量从 dtype float64 转换为 layer 的 dtype 的 float32,这是 TensorFlow 2 中的新行为。该层具有 dtype float32,因为它的 dtype 默认为 floatx。
如果您打算在 float32 中运行此层,则可以放心地忽略此警告。如果有疑问,此警告可能仅在您将 TensorFlow 1.X 模型移植到 TensorFlow 2 时才会出现。
要将所有层更改为默认具有 dtype float64,请调用 tf.keras.backend.set_floatx('float64')。要仅更改此图层,请将 dtype='float64' 传递给图层构造函数。如果您是该层的作者,您可以通过将 autocast=False 传递给基础层构造函数来禁用自动转换。
可以使用 Tensorflow 进行带有8bit input 的训练,这称为量化。但在大多数情况下(即,除非您需要将模型部署在边缘设备上),这是具有挑战性且不必要的。
tl;dr 将您的意见保留在 np.float32。另见this post。