from tensorflow.keras import layers
from tensorflow.keras import initializers
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.utils.np_utils import to_categorical
from keras.datasets import mnist
from keras.utils import plot_model
#(X_train,y_train),(X_test,y_test)=mnist.load_data() #默认是从网站上下载,不过比较慢,建议使用下面的方式
import numpy as np
with np.load('mnist.npz', allow_pickle=True) as f:
X_train, y_train = f['x_train'], f['y_train']
X_test, y_test = f['x_test'], f['y_test']
#print(X_train.shape,y_train.shape)
X_train = X_train.reshape(-1,28, 28,1)
X_test = X_test.reshape(-1, 28, 28,1)
#print(X_train.shape,y_train.shape)
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
print(X_train.shape,y_train.shape)
model = Sequential()
#layer2
model.add(Conv2D(6, (3,3),strides=(1,1),input_shape=X_train.shape[1:],data_format='channels_last',padding='valid',activation='relu',kernel_initializer='uniform'))
#layer3
model.add(MaxPooling2D((2,2)))
#layer4
model.add(Conv2D(16, (3,3),strides=(1,1),data_format='channels_last',padding='valid',activation='relu',kernel_initializer='uniform'))
#layer5
model.add(MaxPooling2D(2,2))
#layer6
model.add(Conv2D(120, (5,5),strides=(1,1),data_format='channels_last',padding='valid',activation='relu',kernel_initializer='uniform'))
model.add(Flatten())
#layer7
model.add(Dense(84,activation='relu'))
#layer8
model.add(Dense(10,activation='softmax'))
#print
model.summary()
model.compile(optimizer='sgd',loss='categorical_crossentropy',metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
import os
filepath = "model_{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True)
print("train____________")
#model.fit(X_train,y_train,epochs=1,batch_size=128,callbacks=[checkpoint])
model.fit(X_train,y_train,epochs=1,batch_size=128)
print("test_____________")
loss,acc=model.evaluate(X_test,y_test)
print("loss=",loss)
print("accuracy=",acc)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from keras.utils import plot_model
plot_model(model,to_file='example.png',show_shapes=True)
lena = mpimg.imread('example.png') # 读取和代码处于同一目录下的 lena.png
#此时 lena 就已经是一个 np.array 了,可以对它进行任意处理
lena.shape #(512, 512, 3)
plt.imshow(lena) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show()
config = model.get_config() # return dict
model = model.from_config(config)
model.save('model.h5') #这里面包含网络和权重的全部信息,可以直接加载进来,model = load()
model.save_weights("model_weights.h5") #这里只有的权重的信息,必须要建立网络之后,再加载权重,才能使用
len(model.layers)
model.layers[2].bias += 1.0
model.layers[2].kernel *= 1.1
# 返回所有层的权重系数,
weights = model.get_weights() #return list
#并保存成numpy array
weight = np.array(weights)
#得到具体某一层的权重系数
#对于BN层,layer.get_weights()返回一个list,为[gamma, beta, mean, std]四个array, 见stackoverflow
#对于卷积层和全连接层,layer.get_weights()返回一个list,为[weight, bias]两个array
for i in model.get_weights():
print(type(i), i.shape)
for j in model.layers:
print(type(j),j.name)
print(model.get_layer('conv2d_1').get_weights())
cnn1_weights = np.array(model.get_layer('conv2d_1').get_weights())
cnn1_weights *= 1.1
#修改之后重新设置回去
model.get_layer('conv2d_1').set_weights(cnn1_weights)