【问题标题】:Does it matter what dtype a numpy array is for input into a tensorflow/keras neural network?numpy 数组输入到 tensorflow/keras 神经网络的 dtype 是否重要?
【发布时间】:2020-12-05 01:13:16
【问题描述】:

如果我采用 tensorflow.keras 模型并调用 model.fit(x, y)(其中xy 是 numpy 数组),那么 dtype numpy 数组是什么有关系吗?我是否最好让dtype 尽可能小(例如,int8 用于二进制数据)还是这会给 tensorflow/keras 额外的工作以将其转换为浮点数?

【问题讨论】:

    标签: python numpy tensorflow machine-learning keras


    【解决方案1】:

    您应该将输入转换为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

    【讨论】:

    • 你在哪个版本的 TF 上运行它?我不记得看到过那个警告。
    • 张量流 2.1 版
    • 如果我的输入都是布尔数组,我可以将其转换为 dtype bool_ 吗?
    • @MathieuChâteauvert 将其转换为tf.int32,然后将其转换为tf.float32
    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2018-04-27
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多