我们用python代码构建CNN
- 导入相关的包:
# import relevant packages
from keras.datasets import mnist import matplotlib.pyplot as plt
%matplotlib inline import numpy as np
from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense
from keras.layers import Dropout from keras.utils import np_utils from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D from keras.utils import np_utils
from keras import backend as K from keras import regularizers
- 创建简单的数据集:
# Create a simple dataset X_train=np.array([[[1,2,3,4],[2,3,4,5],[5,6,7,8],[1,3,4,5]],
[[-1,2,3,-4],[2,-3,4,5],[-5,6,-7,8],[-1,-3,-4,-5]]])
y_train=np.array([0,1])
- 归一化输入:
X_train = X_train / 8
- 独热编码输出:
y_train = np_utils.to_categorical(y_train)
- 一旦有了只有两个 4 × 4大小的输入和两个输出的数据集,我们首先改变输入形状到要求的格式 (即:样本数,图像高, 图像宽,图像通道数):
X_train = X_train.reshape(X_train.shape[0],X_train.shape[1], X_train.shape[1],1 ).astype('float32')
- 模建模型:
model = Sequential()
model.add(Conv2D(1, (3,3), input_shape=(4,4,1), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten())
model.add(Dense(10, activation='relu')) model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
- 拟合模型:
model.fit(X_train, y_train, epochs=100, batch_size=2, verbose=1)
上面模型的不同层如下:
model.layers
不同层的名字和形状如下:
names = [weight.name for layer in model.layers for weight in layer.weights] weights = model.get_weights()
打印zip(names, weights)的名字和权重: print(name, weight.shape)
某个层的权重用如下方法提取:
model.layers[0].get_weights()
第一个输入的预测计算如下:
model.predict(X_train[0].reshape(1,4,4,1))
现在我们知道对于数字0的概率为0.89066。