Ha importanza quale dtype sia un array numpy per l'input in una rete neurale tensorflow / keras?

Aug 15 2020

Se prendo un modello tensorflow.keras e chiamo model.fit(x, y)(dove xe ysono gli array numpy), importa quale sia dtypel'array numpy? È meglio rendere il dtypepiù piccolo possibile (ad esempio int8per i dati binari) o questo dà a tensorflow / keras un lavoro extra per lanciarlo su un float?

Risposte

1 NicolasGervais Aug 15 2020 at 17:20

Dovresti np.float32trasmettere il tuo input a , questo è il dtype predefinito per Keras. Cercalo:

import tensorflow as tf
tf.keras.backend.floatx()
'float32'

Se dai un input a Keras np.float64, si lamenterà:

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)

ATTENZIONE: tensorflow: il layer my_model sta eseguendo il cast di un tensore di input da dtype float64 al dtype del layer float32, che è un nuovo comportamento in TensorFlow 2. Il layer ha dtype float32 perché dtype è predefinito su floatx. Se intendevi eseguire questo livello in float32, puoi tranquillamente ignorare questo avviso. In caso di dubbio, questo avviso è probabilmente un problema solo se si sta eseguendo il porting di un modello TensorFlow 1.X su TensorFlow 2. Per modificare tutti i layer in modo che dtype float64 per impostazione predefinita, chiamare tf.keras.backend.set_floatx('float64'). Per cambiare solo questo livello, passare dtype = 'float64' al costruttore del livello. Se sei l'autore di questo livello, puoi disabilitare l'autocasting passando autocast = False al costruttore del livello di base.

È possibile utilizzare Tensorflow per l'addestramento con un input a 8 bit , chiamato quantizzazione. Ma è impegnativo e non necessario nella maggior parte dei casi (ovvero, a meno che non sia necessario distribuire i modelli su dispositivi periferici).

tl; dr mantieni il tuo input np.float32. Vedi anche questo post .