import numpy as np
from keras.datasets import mnist
from keras.models import sequential
from keras.layers import dense, dropout, flatten
from keras.layers.convolutional import conv2d, maxpooling2d
def load_data():
path = 「data/mnist.npz」
f = np.load(path)
x_train, y_train = f[『x_train』], f[『y_train』]
x_test, y_test = f[『x_test』], f[『y_test』]
f.close()
return (x_train, y_train), (x_test, y_test)
def train_y(y):
y_ohe = np.zeros(10)
y_ohe[y] = 1
return y_ohe
『』『讀入資料』』』
(x_train, y_train), (x_test, y_test) = load_data()
print(x_train[0].shape)
print(y_train[0])
x_train = x_train.reshape(x_train.shape[0],28,28,1).astype(『float32』)
x_test = x_test.reshape(x_test.shape[0],28,28,1).astype(『float32』)
x_train /= 255
x_test /=255
『』『onehot編碼』』』
y_train_ohe = np.array([train_y(y_train[i]) for i in range(len(y_train))])
y_test_ohe = np.array([train_y(y_test[i]) for i in range(len(y_test))])
『』『搭建卷積神經網路』』』
model = sequential()
model.add(conv2d(filters=64, kernel_size=(3,3),strides=(1,1), padding=『same』, input_shape=(28,28,1),activation=「relu」))#新增卷積層
model.add(maxpooling2d(pool_size=(2,2)))#新增池化層
model.add(dropout(0.5))#設定dropout層
model.add(conv2d(filters=128, kernel_size=(3,3),strides=(1,1), padding=『same』, input_shape=(28,28,1),activation=「relu」))#新增卷積層
model.add(maxpooling2d(pool_size=(2,2)))#新增池化層
model.add(dropout(0.5))#設定dropout層
model.add(conv2d(filters=256, kernel_size=(3,3),strides=(1,1), padding=『same』, input_shape=(28,28,1),activation=「relu」))#新增卷積層
model.add(maxpooling2d(pool_size=(2,2)))#新增池化層
model.add(dropout(0.5))#設定dropout層
model.add(flatten())#將當前節點展平
『』『構造全連線神經網路層』』』
model.add(dense(128,activation=『relu』))
model.add(dense(64,activation=『relu』))
model.add(dense(32,activation=『relu』))
model.add(dense(10,activation=『softmax』))
『』『定義損失函式,分類問題一般使用交叉熵』』』
model.compile(loss=『categorical_crossentropy』, optimizer=『adagrad』, metrics=[『accuracy』])
『』『批量放入資料,進行訓練』』』
model.fit(x_train,y_train_ohe, validation_data=(x_test, y_test_ohe),epochs=20,batch_size=128)
『』『測試集評價模型準確度』』』
scores = model.evaluate(x_test,y_test_ohe,verbose=0)
print(scores)
卷積神經網路 Keras 由淺入深
python mathematics 卷積神經網路能夠有效的處理影象檔案,當然換一種說法就是能夠有效處理矩陣。其關鍵部分就是 卷積核 過濾器 的生成。當然還有一些其他的基礎操作。對於卷積核 卷積核的特徵 init filters,kernel size,strides 1 1 padding val...
keras卷積神經網路舉例
特徵圖深度在增加 從32到128,但尺寸在變小 from keras import layers from keras import model 輸入尺寸為150 150 3,展平後是7 7 128 model model.sequential 二維卷積核 提取的圖塊大小 一般3 3 9個特徵向量,...
Keras實現卷積神經網路
1 coding utf 8 2 3created on sun jan 20 11 25 29 201945 author zhen 6 78 import numpy as np 9from keras.datasets import mnist 10from keras.models impo...