import tensorflow as tf
import os
"""
模型持久化:
含义:将当前训练好的模型图 和 权重保存到本地磁盘中,方便后续的使用。
1、服务器训练好了一个模型,迁移到 移动端使用;
2、深度学习训练都很耗时,耗钱。 可以迁移学习。
"""
def train():
with tf.Graph().as_default():
v1 = tf.get_variable(
'v1', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
v2 = tf.get_variable(
'v2', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
rezult = v1 + v2
saver = tf.train.Saver()
save_file = './models/ai20/model.ckpt'
dirpath = os.path.dirname(save_file)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
print('成功创建文件夹:{}'.format(dirpath))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run([v1, v2, rezult]))
"""
[array([0.25989017], dtype=float32),
array([-0.12384889], dtype=float32),
array([0.13604128], dtype=float32)]
"""
saver.save(sess=sess, save_path=save_file)
print('变量成功保存至:{}'.format(save_file))
def restore_var():
with tf.Graph().as_default():
v1 = tf.get_variable(
'v1', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
v2 = tf.get_variable(
'v2', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
rezult = v1 + v2
saver = tf.train.Saver()
save_file = './models/ai20/model.ckpt'
dirpath = os.path.dirname(save_file)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
print('成功创建文件夹:{}'.format(dirpath))
with tf.Session() as sess:
saver.restore(sess, save_path=save_file)
print(sess.run([v1, v2, rezult]))
"""
[array([0.25989017], dtype=float32),
array([-0.12384889], dtype=float32),
array([0.13604128], dtype=float32)]
"""
if __name__ == '__main__':
restore_var()