我已经尝试将tensorflow mobilenetv2模型转换为tflite模型很长时间了,但我在kaggle中遇到了很多问题。我认为当模型运行所有纪元时,我已经没有时间了,而且很难保存模型并转换为 tflite 模型。所以现在我将模型下载到我的本地计算机上。有什么方法可以在命令行中将本地文件转换为 tflite 模型吗?
我尝试过以下代码但无济于事
tflite_convert = --saved_model_dir=/Users/ns/Downloads/Mobilenet/Mobilenet_V2_LR.h5 --output_file=/Users/ns/Downloads/Mobilenetet/mobilenet.tflite
顺便说一句,这是我的模型--
#import lines
# Load the CSV with pandas to get the image paths and targets
# Split the data into a training and validation set
# Convert the image paths and targets into TensorFlow Datasets
# Define the model architecture using MobileNetV2 as base
base_model = MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
base_model.trainable = True # Fine-tune all layers
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x) # Adjusted dense layer
speed_output = Dense(1, name='speed')(x)
angle_norm_output = Dense(1, name='angle_norm')(x)
model = Model(inputs=base_model.input, outputs=[speed_output, angle_norm_output])
# Compile the model with RMSprop optimizer
# Define a learning rate scheduler callback
# Define callbacks
# Train the model with callbacks
history = model.fit(train_dataset, epochs=30, validation_data=val_dataset, callbacks=callbacks)
# Convert the trained model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('trained_mobilenetv2.tflite', 'wb') as f:
f.write(tflite_model)
print("Trained TensorFlow Lite model saved successfully.")
我可以使用 PyTorch 轻松转换 mobilenetv2 https://github.com/google-ai-edge/ai-edge-torch:
import ai_edge_torch
import torch
import torchvision.models as models
mobilenet = models.mobilenet_v2(pretrained=True)
edge_model = ai_edge_torch.convert(mobilenet.eval(), (torch.randn(1, 3, 224, 224),))
edge_model.export("mobilenetv2.tflite")
也许这对你来说会更容易