将Keras模型导出到TensorFlow

时间:2018-04-12 16:42:12

标签: python tensorflow keras

我正在尝试将Keras模型导出到TensorFlow。

Keras版本2.1.4 TF版本1.3.0 Numpy版本1.13.3

这是模型:

img_width, img_height = 150, 150
batch_size = 32
samples_per_epoch = 1000
validation_steps = 300
nb_filters1 = 32
nb_filters2 = 64
conv1_size = 3
conv2_size = 2
pool_size = 2
classes_num = 3
lr = 0.0004

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3)))
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())  # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Dense(classes_num, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer=optimizers.RMSprop(lr=lr),
metrics=['accuracy'])

这是导出代码:

from tensorflow.python import keras
estimator_model = keras.estimator.model_to_estimator(keras_model=model)

这是错误:

  

INFO:tensorflow:使用提供的Keras模型。 INFO:tensorflow:使用   默认配置。警告:tensorflow:使用临时文件夹作为模型   目录:/home/dsxuser/.tmp/tmpbgYQQa INFO:tensorflow:使用config:   {'_save_checkpoints_secs':600,'_ session_config':无,   '_keep_checkpoint_max':5,'_ task_type':'worker',   '_global_id_in_cluster':0,'_ is_chief':是的,'_ cluster_spec':   ,'_evaluation_master':'','_ save_checkpoints_steps':   无,'_ keep_checkpoint_every_n_hours':10000,'_ service':无,   '_num_ps_replicas':0,'_ tf_random_seed':无,'_ master':'',   '_num_worker_replicas':1,'_ task_id':0,'_ log_step_count_steps':   100,'_ model_dir':'/ home / dsxuser / .tmp / tmpbgYQQa',   '_save_summary_steps':100}

     

AttributeErrorTraceback(最近一次调用最后一次)    in()         1来自tensorflow.python导入keras   ----> 2 estimator_model = keras.estimator.model_to_estimator(keras_model = model)

     

/opt/conda/envs/DSX-Python27/lib/python2.7/site-packages/tensorflow/python/keras/_impl/keras/estimator.pyc   在model_to_estimator中(keras_model,keras_model_path,custom_objects,   model_dir,config)       476       477 keras_weights = keras_model.get_weights()    - > 478 if keras_model._is_graph_network:       479#TODO(yifeif):将检查点初始化移至scaffold.init_fn       480 _save_first_checkpoint(keras_model,

     

AttributeError:'Sequential'对象没有属性   '_is_graph_network'

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你需要这个 from tensorflow.python.keras import Sequential 你应该使用在tensorflow中实现的keras api而不是直接使用keras api。

答案 1 :(得分:0)

我有同样的问题。我按如下方式导入keras from tensorflow import keras from keras.models import Sequential model = Sequential()

等。那么它就失败了: estimator_model = keras.estimator.model_to_estimator(keras_model=kerasModel())

错误:

/usr/local/lib/python2.7/dist-packages/tensorflow/python/keras/_impl/keras/estimator.pyc in model_to_estimator(keras_model, keras_model_path, custom_objects, model_dir, config)
    476 
    477   keras_weights = keras_model.get_weights()
--> 478   if keras_model._is_graph_network:
    479     # TODO(yifeif): move checkpoint initialization to scaffold.init_fn
    480     _save_first_checkpoint(keras_model,

AttributeError: 'Sequential' object has no attribute '_is_graph_network'

我正在使用tensorflow 1.7

我通过明确指定模型的图层找到了解决方案:

def kerasModel():
    # Define the model
    model = keras.models.Sequential()
    #model = Sequential()
    # input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
    # this applies 32 convolution filters of size 3x3 each.
    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3), name="data2d"))
    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu'))
    model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(keras.layers.Dropout(0.25))

    model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(keras.layers.Dropout(0.25))

    model.add(keras.layers.Flatten())
    model.add(keras.layers.Dense(256, activation='relu'))
    model.add(keras.layers.Dropout(0.5))
    model.add(keras.layers.Dense(10, activation='softmax', name='labels'))

    # Compile the model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model

即。通过put keras.layers。在上面的每一行中。以前我曾依赖进口:

#from keras.models import Sequential 
#from keras.layers import Dense, Dropout, Flatten 
#from keras.layers import Conv2D, MaxPooling2D 

正如您所看到的,我现在已经注释掉了。请注意,我也放了keras.models。在Sequential()前面也可能是必要的。看看这是否适合你。