我尝试使用以下代码将以下keras模型转换为 tflite ,以便在移动平台中托管。我已经安装了tensorflow版本= 1.12 python版本= 3.6.7 keras版本= 2.2.4 运行此代码后,出现以下错误。
转换器= tf.lite.TFLiteConverter.from_keras_model_file(keras_file) AttributeError:模块'tensorflow'没有属性'lite'
此错误的原因可能是什么,如何解决?
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import tensorflow as tf
# dimensions of our images.
img_width, img_height = 150, 150
train_data_dir = 'D:\\My Projects\\Dataset\\dataset6_2clz\\train'
validation_data_dir = 'D:\\My Projects\\Dataset\\dataset6_2clz\\validation'
nb_train_samples = 75
nb_validation_samples = 50
#epochs = 50
#batch_size = 16
epochs = 5
batch_size = 4
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
# Save tf.keras model in HDF5 format.
keras_file = "7_try.h5"
model.save('7_try.h5')
# Convert to TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
答案 0 :(得分:2)
在tensorflow 1.12中应该是
converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(keras_file)
请参见https://www.tensorflow.org/lite/convert/python_api#pre_tensorflow_1.12 我猜您阅读了以下参考文献https://www.tensorflow.org/lite/convert/python_api,但请注意以下注意事项
注意:这些文档每晚描述TensorFlow中的转换器 发布,使用pip install tf-nightly安装。对于文档描述 较旧的版本参考“从TensorFlow 1.12转换模型”。
此外,有关更多信息,您可以看到此提交消息https://github.com/tensorflow/tensorflow/commit/61c6c84964b4aec80aeace187aab8cb2c3e55a72