Advertisement

python模型输出结果_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='validation loss', verbose=1, save_best_only=True, mode='min')

print(model.get_config())

该层神经元采用VarianceScaling初始化器对权重进行归一化处理,默认情况下实现了对偏置项的学习能力。
该层神经元配置了单位数设置为10的全连接层。
该层神经元采用了均匀分布作为激活函数的缩放因子设置。
第一个全连接层实现了对批量大小N的数据输入处理能力。
第二个全连接层采用了Softmax激活函数以实现分类任务目标。
第一个全连接层通过ReLU激活函数实现了非线性特征提取能力。
第二个全连接层通过指数型衰减权重正则化方法实现了模型泛化能力的有效提升。

模型拟合(使用指定的超参数配置):使用训练输入数据(x_train)和训练目标数据(y_train),设置批量大小为128;在每一轮迭代中执行一次epoch;并使用预定义回调函数[checkpoint]以及验证输入数据(x_valid)和验证目标数据(y_valid)进行监控。

model.train(training_dataset=y_train, target_labels=y_train, epoch_count=1, validation_set=(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:\weights.h5", by_name=False) # 根据名称匹配及各层权重

查看中间结果,必须要先声明个函数式模型

dense_1_model = Model(inputs=input_tensors, outputs=layers.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模型参数设置、模型保存以及中间结果输出的操作步骤已经被我进行了详细讲解。希望这些内容能够为广大学习者提供一些参考价值,并希望大家能够持续关注脚本之家以获取更多学习资源。

全部评论 (0)

还没有任何评论哟~