keras 模型参数,模型保存,中间结果输出操作
作者:姚贤贤 发布时间:2023-06-05 09:52:33
标签:keras,模型,参数,保存,结果
我就废话不多说了,大家还是直接看代码吧~
'''
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过之后的图像:
原始图像:
经过一层conv以后,输出其中4张图片:
来源:https://blog.csdn.net/u011311291/article/details/79963831


猜你喜欢
- 前言:Python smtplib 教程:展示了如何使用 smtplib 模块在 Python 中发送电子邮件。 要发送电子邮件,我们使用
- 什么是接口测试接口测试主要用于检测外部系统与内部系统之间,以及系统内部各 个子系统之间的交互点。其测试的重点是,检查数据的交换、传递和控 制
- 起因是因为公司要开发一款自动登录某网站的助手工具提供给客户使用,要使用到selenium,所以选择了pyqt5的方式来开发这个C/S架构的客
- 这篇文章主要介绍了Python如何使用函数做字典的值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- 本文实例讲述了Python使用百度翻译开发平台实现英文翻译为中文功能。分享给大家供大家参考,具体如下:#coding=utf8import
- SQL Server常见的问题主要是SQL问题造成,常见的主要是CPU过高和阻塞。一、CPU过高的问题1、查询系统动态视图查询执行时间长的s
- 目录一、数据库引擎1.1 查看数据库引擎1.2 修改默认数据库引擎二、数据库字符集2.1 查看字符集2.2 修改字符集一、数据库引擎1.1
- 这是一个很久以前的例子,现在在整理资料时无意发现,就拿出来再改写分享。1.需求 1.1 基本需求: 根据输入的地址关键字,搜索出完
- 在《javascript设计模式》中对这种方法作了比较详细的描述,实现方法的链式调用,只须让在原型中定义的方法都返回调用这些方法的实例对象的
- 这篇文章主要介绍了基于python调用psutils模块过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值
- 一主一从: Master: OS:centos release 5.6 DB:mysql 5.5.8 IP:192.168.1.2 Slav
- 这是毕业校招二面时遇到的手写编程题,当时刚刚开始学习python,整个栈写下来也是费了不少时间。毕竟语言只是工具,只要想清楚实现,使用任何语
- 使用consul四大特性1. 服务发现:利用服务注册,服务发现功能来实现服务治理。2. 健康检查:利用consul注册的检查检查函数或脚本来
- 看代码吧~import pymongofrom dateutil import parserdateStr = "2019-05-
- 1.现在我本机系统已内置python2.62.下载进行源码安装复制链接下载到/root/mypackage,解压接着mkdir /usr/l
- 需要写个js滑动展开折叠(收缩)的效果,搜索到无忧脚本的一篇贴子,稍加修改了下使其在FF也可应用,代码如下: <
- 本文实例讲述了python中__call__内置函数的用法。分享给大家供大家参考。具体分析如下:对象通过提供__call__(slef, [
- 如下所示:<div id="app"> <h1>我是直接写在构造器里的模板1</h1&g
- 一、固定费用问题案例解析1.1、固定费用问题(Fixed cost problem)固定费用问题,是指求解生产成本最小问题时,总成本包括固定
- 代码import turtleturtle.bgcolor("black")turtle.pensize(2)sizeh