keras 模型参数,模型保存,中间结果输出操作


Posted in Python onJuly 06, 2020

我就废话不多说了,大家还是直接看代码吧~

'''
Created on 2018-4-16
'''
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.models import Model
from keras.callbacks import ModelCheckpoint,Callback
import numpy as np
import tflearn
import tflearn.datasets.mnist as mnist

x_train, y_train, x_test, y_test = mnist.load_data(one_hot=True)
x_valid = x_test[:5000]
y_valid = y_test[:5000]
x_test = x_test[5000:]
y_test = y_test[5000:]
print(x_valid.shape)
print(x_test.shape)

model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=784))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
       optimizer='sgd',
       metrics=['accuracy'])
filepath = 'D:\\machineTest\\model-ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5'
# filepath = 'D:\\machineTest\\model-ep{epoch:03d}-loss{loss:.3f}.h5'
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
print(model.get_config())
# [{'class_name': 'Dense', 'config': {'bias_regularizer': None, 'use_bias': True, 'kernel_regularizer': None, 'batch_input_shape': (None, 784), 'trainable': True, 'kernel_constraint': None, 'bias_constraint': None, 'kernel_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1.0, 'distribution': 'uniform', 'mode': 'fan_avg', 'seed': None}}, 'activity_regularizer': None, 'units': 64, 'dtype': 'float32', 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'activation': 'relu', 'name': 'dense_1'}}, {'class_name': 'Dense', 'config': {'bias_regularizer': None, 'use_bias': True, 'kernel_regularizer': None, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_constraint': None, 'bias_constraint': None, 'kernel_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1.0, 'distribution': 'uniform', 'mode': 'fan_avg', 'seed': None}}, 'activity_regularizer': None, 'trainable': True, 'units': 10, 'activation': 'softmax', 'name': 'dense_2'}}]
# model.fit(x_train, y_train, epochs=1, batch_size=128, callbacks=[checkpoint],validation_data=(x_valid, y_valid))
model.fit(x_train, y_train, epochs=1,validation_data=(x_valid, y_valid),steps_per_epoch=10,validation_steps=1)
# score = model.evaluate(x_test, y_test, batch_size=128)
# print(score)
# #获取模型结构状况
# model.summary()
# _________________________________________________________________
# Layer (type)         Output Shape       Param #  
# =================================================================
# dense_1 (Dense)       (None, 64)        50240(784*64+64(b))   
# _________________________________________________________________
# dense_2 (Dense)       (None, 10)        650(64*10 + 10 )    
# =================================================================
# #根据下标和名称返回层对象
# layer = model.get_layer(index = 0)
# 获取模型权重,设置权重model.set_weights()
weights = np.array(model.get_weights())
print(weights.shape)
# (4,)权重由4部分组成
print(weights[0].shape)
# (784, 64)dense_1 w1
print(weights[1].shape)
# (64,)dense_1 b1
print(weights[2].shape)
# (64, 10)dense_2 w2
print(weights[3].shape)
# (10,)dense_2 b2

# # 保存权重和加载权重
# model.save_weights("D:\\xxx\\weights.h5")
# model.load_weights("D:\\xxx\\weights.h5", by_name=False)#by_name=True,可以根据名字匹配和层载入权重

# 查看中间结果,必须要先声明个函数式模型
dense1_layer_model = Model(inputs=model.input,outputs=model.get_layer('dense_1').output)
out = dense1_layer_model.predict(x_test)
print(out.shape)
# (5000, 64)

# 如果是函数式模型,则可以直接输出
# import keras
# from keras.models import Model
# from keras.callbacks import ModelCheckpoint,Callback
# import numpy as np
# from keras.layers import Input,Conv2D,MaxPooling2D
# import cv2
# 
# image = cv2.imread("D:\\machineTest\\falali.jpg")
# print(image.shape)
# cv2.imshow("1",image)
# 
# # 第一层conv
# image = image.reshape([-1, 386, 580, 3])
# img_input = Input(shape=(386, 580, 3))
# x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
# x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
# x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# model = Model(inputs=img_input, outputs=x)
# out = model.predict(image)
# print(out.shape)
# out = out.reshape(193, 290,64)
# image_conv1 = out[:,:,1].reshape(193, 290)
# image_conv2 = out[:,:,20].reshape(193, 290)
# image_conv3 = out[:,:,40].reshape(193, 290)
# image_conv4 = out[:,:,60].reshape(193, 290)
# cv2.imshow("conv1",image_conv1)
# cv2.imshow("conv2",image_conv2)
# cv2.imshow("conv3",image_conv3)
# cv2.imshow("conv4",image_conv4)
# cv2.waitKey(0)

中间结果输出可以查看conv过之后的图像:

原始图像:

keras 模型参数,模型保存,中间结果输出操作

经过一层conv以后,输出其中4张图片:

keras 模型参数,模型保存,中间结果输出操作

keras 模型参数,模型保存,中间结果输出操作

keras 模型参数,模型保存,中间结果输出操作

keras 模型参数,模型保存,中间结果输出操作

以上这篇keras 模型参数,模型保存,中间结果输出操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python合并字符串的3种方法
May 21 Python
Python 实现简单的shell sed替换功能(实例讲解)
Sep 29 Python
python3使用scrapy生成csv文件代码示例
Dec 28 Python
Django自定义manage命令实例代码
Feb 11 Python
使用python进行文本预处理和提取特征的实例
Jun 05 Python
python爬虫实例详解
Jun 19 Python
详解Python的三种可变参数
May 08 Python
Python多版本开发环境管理工具介绍
Jul 03 Python
Python with用法:自动关闭文件进程
Jul 10 Python
python实现登录密码重置简易操作代码
Aug 14 Python
python自动分箱,计算woe,iv的实例代码
Nov 22 Python
Pytorch实现的手写数字mnist识别功能完整示例
Dec 13 Python
Python自省及反射原理实例详解
Jul 06 #Python
如何通过命令行进入python
Jul 06 #Python
解决TensorFlow调用Keras库函数存在的问题
Jul 06 #Python
python else语句在循环中的运用详解
Jul 06 #Python
Keras模型转成tensorflow的.pb操作
Jul 06 #Python
python如何进入交互模式
Jul 06 #Python
python3.4中清屏的处理方法
Jul 06 #Python
You might like
根德YB400的电路分析
2021/03/02 无线电
分享PHP header函数使用教程
2013/09/05 PHP
利用“多说”制作留言板、评论系统
2015/07/14 PHP
YII Framework框架教程之日志用法详解
2016/03/14 PHP
PHP简单日历实现方法
2016/07/20 PHP
PHP基于imagick扩展实现合成图片的两种方法【附imagick扩展下载】
2017/11/14 PHP
javascript编程起步(第七课)
2007/02/27 Javascript
JQuery的ajax获取数据后的处理总结(html,xml,json)
2010/07/14 Javascript
利用谷歌地图API获取点与点的距离的js代码
2012/10/11 Javascript
jquery 延迟执行实例介绍
2013/08/20 Javascript
dreamweaver 8实现Jquery自动提示
2014/12/04 Javascript
jQuery里filter()函数与find()函数用法分析
2015/06/24 Javascript
javascript中eval解析JSON字符串
2016/02/27 Javascript
JavaScript随机生成颜色的方法
2016/10/15 Javascript
node.js学习之交互式解释器REPL详解
2016/12/08 Javascript
整理关于Bootstrap模态弹出框的慕课笔记
2017/03/29 Javascript
Vue.js在使用中的一些注意知识点
2017/04/29 Javascript
vue cli使用融云实现聊天功能的实例代码
2019/04/19 Javascript
详解vue 动态加载并注册组件且通过 render动态创建该组件
2019/05/30 Javascript
layer.open 子页面弹出层向父页面传输数据的例子
2019/09/26 Javascript
vue 取出v-for循环中的index值实例
2019/11/09 Javascript
Python基于正则表达式实现检查文件内容的方法【文件检索】
2017/08/30 Python
使用Python和Prometheus跟踪天气的使用方法
2019/05/06 Python
使用 PyTorch 实现 MLP 并在 MNIST 数据集上验证方式
2020/01/08 Python
Selenium 滚动页面至元素可见的方法
2020/03/18 Python
python thrift 实现 单端口多服务的过程
2020/06/08 Python
html5摇一摇代码优化包括DeviceMotionEvent等等
2014/09/01 HTML / CSS
HTML5页面无缝闪开的问题及解决方案
2020/06/11 HTML / CSS
百思买美国官网:Best Buy
2016/07/28 全球购物
彪马美国官网:PUMA美国
2017/03/09 全球购物
马来西亚综合购物网站:Lazada马来西亚
2018/06/05 全球购物
2014年寒假社会实践活动心得体会
2014/04/07 职场文书
司法所长先进事迹
2014/06/02 职场文书
2016年植树节红领巾广播稿
2015/12/17 职场文书
个人工作失误的保证书怎么写?
2019/06/21 职场文书
Python绘制分类图的方法
2021/04/20 Python