Renuel Roberts
Renuel Roberts
DIIDevHeads IoT Integration Server
Created by wafa_ath on 10/18/2024 in #middleware-and-os
Segmentation Fault with Flatten() in TensorFlow Lite for Microcontrollers on STM32F746NG
@wafa_ath You're encountering a segmentation fault when running your CNN model on the STM32F746NG board using TensorFlow Lite, specifically when using the Flatten() function. Based on your description, the issue might stem from the fact that Flatten() is not explicitly supported in TensorFlow Lite for Microcontrollers, as it’s not included in the all_ops_resolver.cc file. However Flatten() is a common operation in standard TensorFlow models, it's not supported by TensorFlow Lite for Microcontrollers. However, you can achieve the same functionality by replacing the Flatten() layer with a Reshape layer, which is supported in TensorFlow Lite for Microcontrollers and performs the equivalent operation—flattening a multi-dimensional tensor into a 1D array. Here’s how you can modify your model to replace the Flatten() layer:
model = models.Sequential()
model.add(layers.Conv2D(16, (3, 3), activation='relu', input_shape=(36, 36, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(32, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# Replace Flatten() with Reshape
model.add(layers.Reshape((-1,))) # This layer automatically flattens the tensor

model.add(layers.Dense(8, activation='softmax'))
model.add(layers.Dense(2))

model.summary()

model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model = models.Sequential()
model.add(layers.Conv2D(16, (3, 3), activation='relu', input_shape=(36, 36, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(32, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# Replace Flatten() with Reshape
model.add(layers.Reshape((-1,))) # This layer automatically flattens the tensor

model.add(layers.Dense(8, activation='softmax'))
model.add(layers.Dense(2))

model.summary()

model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
6 replies