tensorflow中保存模型的代码
时间: 2023-09-03 22:15:01 浏览: 36
在 TensorFlow 中,可以使用 `tf.saved_model` 模块保存模型。下面是一个简单的示例:
```python
import tensorflow as tf
# 创建模型
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5)
# 保存模型
tf.saved_model.save(model, 'saved_model')
```
在上面的代码中,`tf.saved_model.save` 函数将模型保存到名为 `saved_model` 的文件夹中。要加载模型,可以使用 `tf.saved_model.load` 函数:
```python
# 加载模型
loaded_model = tf.saved_model.load('saved_model')
```
加载的模型可以像通常一样使用,例如:
```python
# 使用模型进行预测
predictions = loaded_model.predict(x_test)
```