Python之TensorFlow的模型训练保存与加载-3
一、TensorFlow的模型保存和加载,使我们在训练和使用时的一种常用方式。我们把训练好的模型通过二次加载训练,或者独立加载模型训练。这基本上都是比较常用的方式。
二、模型的保存与加载类型有2种
1)需要重新建立图谱,来实现模型的加载
2)独家加载模型
模型的保存与训练加载:
tf.train.Saver(<var_list>,<max_to_keep>)
var_list: 指定要保存和还原的变量,作为一个dict或者list传递
max_to_keep: 指示要保留的最大检查点文件个数。
保存模型的文件:checkpoint文件/检查点文件
method:
save(<session>, <path>)
restore(<session>, <path>)
模型的独立加载:
1、tf.train.import_meta_graph(<meta_graph_or_file>) 读取训练时的数据流图
meta_graph_or_file: *.meta的文件
2、saver.restore(<session>, tf.train.latest_checkpoint(<path>)) 加载最后一次检测点
path: 含有checkpoint的上一级目录
3、graph = tf.get_default_graph() 默认图谱
graph.get_tensor_by_name(<name>) 获取对应数据传入占位符
name: tensor的那么名称,如果没有生命name,则为(placeholder:0), 数字0依次往后推
graph.get_collection(<name>) 获取收集集合
return tensor列表
补充:
如果不知道怎么去获取tensor的相关图谱,可以通过
graph.get_operations() 查看所有的操作符,最好断点查看
三、模型的保存与训练加载
import os
import tensorflow as tf def model_save():
# 1、准备特征值和目标值
with tf.variable_scope("data"):
# 占位符,用于数据传入
x = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x")
# 矩阵相乘必须是二维(为了模拟效果而设定固定值来训练)
y_true = tf.matmul(x, [[0.7]]) + 0.8 # 2、建立回归模型,随机给权重值和偏置的值,让他去计算损失,然后在当前状态下优化
with tf.variable_scope("model"):
# 模型 y = wx + b, w的个数根据特征数据而定,b随机
# 其中Variable的参数trainable可以指定变量是否跟着梯度下降一起优化(默认True)
w = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0), name="w", trainable=True)
b = tf.Variable(0.0, name="b")
# 预测值
y_predict = tf.matmul(x, w) + b # 3、建立损失函数,均方误差
with tf.variable_scope("loss"):
loss = tf.reduce_mean(tf.square(y_true - y_predict)) # 4、梯度下降优化损失
with tf.variable_scope("optimizer"):
# 学习率的控制非常重要,如果过大会出现梯度消失/梯度爆炸导致NaN
train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) # 收集需要用于预测的模型
tf.add_to_collection("y_predict", y_predict) # 定义保存模型
saver = tf.train.Saver() # 通过绘画运行程序
with tf.Session() as sess:
# 存在变量时需要初始化
sess.run(tf.global_variables_initializer()) # 加载上次训练的模型结果
if os.path.exists("model/model/checkpoint"):
saver.restore(sess, "model/model/model") # 循环训练
for i in range(100):
# 读取数据(这里自己生成数据)
x_train = sess.run(tf.random_normal([100, 1], mean=1.75, stddev=0.5, name="x")) sess.run(train_op, feed_dict={x: x_train}) # 保存模型
if (i + 1) % 10 == 0:
print("第%d次训练保存,权重:%f, 偏值:%f" % (((i + 1) / 10), w.eval(), b.eval()))
saver.save(sess, "model/model/model")
四、模型的独立加载
def model_load():
with tf.Session() as sess:
# 1、加载模型
saver = tf.train.import_meta_graph("model/model/model.meta")
saver.restore(sess, tf.train.latest_checkpoint("model/model"))
graph = tf.get_default_graph() # 2、获取占位符
x = graph.get_tensor_by_name("data/x:0") # 3、获取权重和偏置
y_predict = graph.get_collection("y_predict")[0] # 4、读取测试数据
x_test = sess.run(tf.random_normal([10, 1], mean=1.75, stddev=0.5, name="x"))
# 5、预测
for i in range(len(x_test)):
predict = sess.run(y_predict, feed_dict={x: [x_test[i]]})
print("第%d个数据,原值:%f, 预测值:%f" % ((i + 1), x_test[i], predict))
Python之TensorFlow的模型训练保存与加载-3的更多相关文章
- tensorflow 之模型的保存与加载(二)
上一遍博文提到 有些场景下,可能只需要保存或加载部分变量,并不是所有隐藏层的参数都需要重新训练. 在实例化tf.train.Saver对象时,可以提供一个列表或字典来指定需要保存或加载的变量. #!/ ...
- tensorflow 之模型的保存与加载(三)
前面的两篇博文 第一篇:简单的模型保存和加载,会包含所有的信息:神经网络的op,node,args等; 第二篇:选择性的进行模型参数的保存与加载. 本篇介绍,只保存和加载神经网络的计算图,即前向传播的 ...
- tensorflow 之模型的保存与加载(一)
怎样让通过训练的神经网络模型得以复用? 本文先介绍简单的模型保存与加载的方法,后续文章再慢慢深入解读. #!/usr/bin/env python3 #-*- coding:utf-8 -*- ### ...
- tensorflow模型的保存与加载
模型的保存与加载一般有三种模式:save/load weights(最干净.最轻量级的方式,只保存网络参数,不保存网络状态),save/load entire model(最简单粗暴的方式,把网络所有 ...
- [深度学习] Pytorch(三)—— 多/单GPU、CPU,训练保存、加载模型参数问题
[深度学习] Pytorch(三)-- 多/单GPU.CPU,训练保存.加载预测模型问题 上一篇实践学习中,遇到了在多/单个GPU.GPU与CPU的不同环境下训练保存.加载使用使用模型的问题,如果保存 ...
- pytorch 中模型的保存与加载,增量训练
让模型接着上次保存好的模型训练,模型加载 #实例化模型.优化器.损失函数 model = MnistModel().to(config.device) optimizer = optim.Adam( ...
- (sklearn)机器学习模型的保存与加载
需求: 一直写的代码都是从加载数据,模型训练,模型预测,模型评估走出来的,但是实际业务线上咱们肯定不能每次都来训练模型,而是应该将训练好的模型保存下来 ,如果有新数据直接套用模型就行了吧?现在问题就是 ...
- pytorch_模型参数-保存,加载,打印
1.保存模型参数(gen-我自己的模型名字) torch.save(self.gen.state_dict(), os.path.join(self.gen_save_path, 'gen_%d.pt ...
- fashion_mnist多分类训练,两种模型的保存与加载
from tensorflow.python.keras.preprocessing.image import load_img,img_to_array from tensorflow.python ...
随机推荐
- 读入优化&输出优化
读入优化 int read() { ; ') ; '; ') num=num*+c-'; return ff*num; } 输出优化 void write(int x) { ) { putchar(' ...
- Spring AOP的实现记录操作日志
适用场景: 记录接口方法的执行情况,记录相关状态到日志中. 注解类:LogTag.java package com.lichmama.spring.annotation; import java.la ...
- var a = function(){}和var a = function(){}();的区别
var a = function(){ ... ... ... } 声明方法. var a = function(){ ... ... ... }(); 声明方法并执行 demo: var u = f ...
- python去除BOM头\ufeff等特殊字符
1.\ufeff 字节顺序标记 去掉\ufeff,只需改一下编码就行,把UTF-8编码改成UTF-8-sigwith open(file_path, mode='r', encoding='UTF-8 ...
- checkbox与label内的文字垂直居中的解决方案
<label style="float:left;margin-top:5px;margin-left:10px;cursor:pointer"><input t ...
- Python之pandas读取mysql中文乱码问题
# -*- coding: utf-8 -*- # author:baoshan import pandas as pd import pymysql config = { "host&qu ...
- opencv yuvNV21转RGB
void yuv420Torgb() { FILE *fp = fopen("D:\\1.yuv","rb"); ; ; uchar *yuvdata = / ...
- IfcWallStandardCase 构件吊装模拟
wall_node = (osg::Node*)(index_node->clone(osg::CopyOp::DEEP_COPY_ALL));vc_mobileCrane->tranMo ...
- App installation failed (A valid provisioning profile for this executable was not found)
真机调试build success ,App installation failed (A valid provisioning profile for this executable was not ...
- python初级(302) 3 easygui简单使用二
一.复习 1.easygui 信息提示对话框 2.easygui 是否对话框 二.easygui其它组件 1.选择对话框:choicebox(msg, title, choices) import e ...