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

 更新时间:2020年07月06日 16:22:41   作者:姚贤贤  
这篇文章主要介绍了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张图片:

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

相关文章

  • Python 获取ftp服务器文件时间的方法

    Python 获取ftp服务器文件时间的方法

    今天小编就为大家分享一篇Python 获取ftp服务器文件时间的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • 海王小姐姐悄悄问我怎么在PC端登录多个微信

    海王小姐姐悄悄问我怎么在PC端登录多个微信

    这篇文章主要介绍了怎么在PC端登录多个微信号,众所周知pc端一般只能登陆一个微信号,可这年头谁还只有一个号,又不能同时用两台电脑,这篇文章带给你答案
    2021-08-08
  • Linux环境下GPU版本的pytorch安装

    Linux环境下GPU版本的pytorch安装

    使用默认的源地址下载速度很慢,所以一般都是使用国内源,今天花了点时间配置安装,所以记录一下,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍

    python代码 if not x: 和 if x is not None: 和 if not x is None:使用

    这篇文章主要介绍了python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍,需要的朋友可以参考下
    2016-09-09
  • Python中的hashlib模块解析

    Python中的hashlib模块解析

    这篇文章主要介绍了Python中的hashlib模块解析,hashlib是一个提供字符加密功能的模块,包含MD5和SHA的加密算法,具体支持md5,sha1, sha224, sha256, sha384, sha512等算法, 该模块在用户登录认证方面应用广泛,对文本加密也很常见,需要的朋友可以参考下
    2023-09-09
  • Python实现在线程里运行scrapy的方法

    Python实现在线程里运行scrapy的方法

    这篇文章主要介绍了Python实现在线程里运行scrapy的方法,涉及Python线程操作的技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • python list格式数据excel导出方法

    python list格式数据excel导出方法

    今天小编就为大家分享一篇python list格式数据excel导出方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python实现对PPT文件进行截图操作的方法

    Python实现对PPT文件进行截图操作的方法

    这篇文章主要介绍了Python实现对PPT文件进行截图操作的方法,涉及Python操作幻灯片的相关技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • python中numpy.zeros(np.zeros)的使用方法

    python中numpy.zeros(np.zeros)的使用方法

    下面小编就为大家带来一篇python中numpy.zeros(np.zeros)的使用方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • Python批量加密Excel文件的实现示例

    Python批量加密Excel文件的实现示例

    在日常工作中,保护敏感数据是至关重要的,本文主要介绍了Python批量加密Excel文件的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2023-12-12

最新评论