I am building a CNN classification model using tensorflow and python. The model has an input shape of [1, 50, 7] consisting the first column of timestamp, and sensor values for the rest of the columns. The output value is either 0 or 1 to specify motion of left or right. Then, I export the model as TFLite model and used it in Flutter using the tflite_flutter package (https://pub.dev/packages/tflite_flutter).
When I run using interpreter run, the output of the data is always 0.0. However, when I run using python, I noticed that after reading a csv data, I needed to add
input_data = input_data.astype('float32')
to properly run the model and it output a value in range of 0 to 1, which is what I wanted, or else it will output that it cannot get tensor due to getting FLOAT64 instead of FLOAT32. So, I tried to convert my data into float32 using the Float32List in Flutter, but the result is still 0.0.
List<Float32List> group32Float = [];
for (var i = 0; i < 50; i++) {
group32Float.add(Float32List.fromList(group[i]));
}
interpreter!.run([group32Float], [output]);
My model is as such:
input_shape = (50, 7)
model = Sequential()
model.add(Conv1D(filters=32, kernel_size=3, activation='relu', padding='same', input_shape=input_shape))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.25))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(units=64, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(units=32, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
optimizer = Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
early_stop = EarlyStopping(monitor='val_loss', patience=100)
model.fit(X_train, y_train, epochs=1000, validation_data=(X_val, y_val), callbacks=[early_stop])
Then saved as TFLite:
model.save('model', save_format='tf')
converter = tf.lite.TFLiteConverter.from_saved_model('model')
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
My question is: Why is my output in Flutter always 0.0?
For anyone having trouble with the same problem, I've found a solution. I realized that I haven't initially set my input data into the correct type which in my case is:
List<List<double>> input
Try checking your variable type of input and output and make sure it's the correct type to send into the model.