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
0
投稿
猜你喜欢
- 一、连接MYSQL:格式: mysql -h主机地址 -u用户名 -p用户密码1、例1:连接到本机上的MYSQL。首先在打开DOS窗口,然后
- 很多开发人员对于IIS和ASP.NET的安装等问题困扰,特此做下面的小总结,请大家多交流!iis 坏了修复办法!一般IIS运行不了ASP.N
- PHP 过滤器PHP 过滤器用于验证和过滤来自非安全来源的数据,比如用户的输入。什么是 PHP 过滤器PHP 过滤器用于验证和过滤来自非安全
- 对开区间和闭区间的理解对于开区间,本身已经不包含两端点值,所以根本满足不了连续的第一个要求,所以要说某一开区间连续,我们说是函数在这一开区间
- 简介HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-
- 一、增强的可扩展性 Oracle9i Real Application Clusters是Oracle的下一代并行服务器系列产品。Oracl
- fmtfmt是go语言中的格式化输入输出库,其中主要分为两个部分,分别是输出部分和输入部分。输出PrintPrint函数的主要功能是输出,和
- 小试牛刀:1.需要python如何读取文件2.需要python操作list3.需要使用split()对字符串进行分割代码运行截图 :代码(c
- window.showModalDialog() 使用方法:var returnValue = window.showModalDialog
- 基于微信可以做很多有意思的练手项目,看了这张速查表你就会发现,可以做的事情超过你的想象。有一次我想要统计微信群里哪些同学在北京,但发现直接问
- MySQL安装文件已被广泛应用但是也在不断的更新,这里介绍MySQL安装文件设置使用,帮助大家安装更新MySQL安装文件系统。Fedora5
- 侧边栏在响应式设计中起到很大的作用,当屏幕小到手机的屏幕时,能够自适应屏幕大小的侧边栏固然能够为网站添加色彩,那么在Bootstrap的框架
- 每周的《午间欢乐购》和《周末疯狂购》,已经成为视觉组的固定需求。从开始接触到现在5个月的时间里,思维也和这些小小banner逐渐碰撞出火花。
- 1.由于数据库设计问题造成SQL数据库新增数据时超时症状:Microsoft OLE DB Provider for SQL Server
- 今天跟大家分享一下,如何通过Python实现一个轻量级的库来获取电脑上连接的Android设备信息,为什么说轻量呢因为整个库也就4KB,相比
- 首先你得引入bootstrap与jquery推荐一个CDN:http://cdn.gbtags.com/index.html然后就是开始编写
- 用于序列化的两个模块json:用于字符串和Python数据类型间进行转换pickle: 用于python特有的类型和python的数据类型间
- 一、步骤要从 JPEG 图像中获取经纬度信息,可以使用 Python 的 PIL(Python Imaging Library)库。以下是一
- 在这篇文章里,我们将会探索如何使用Python语言作为一个工具来检测Linux系统各种运行信息。让我们一起来学习吧。哪种Python?当我提
- 相信大家都知道html和css,知道html结构和css表现分离,知道html语义化,这些都是这几年的热门关键字。语义化的html在国内也是