keras实现类似 VGG 的卷积神经网络

import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten
from keras.layers import Conv2D,MaxPool2D
from keras.optimizers import SGD

#生成虚拟数据
#训练集100个100*100,3维的数据,标签为100个范围0~9的1维数据
#同理可得测试数据
x_train = np.random.randn((100,100,100,3))
y_train = keras.utils.to_categorical(np.random.randint(10,size=(100,1)),num_classes=10)
x_test = np.random.random((20, 100, 100, 3))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)

#构造序列模型
model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(100,100,3)))
model.add(Conv2D(32,(3,3),activation='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64,(3,3),activation='relu'))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))

#Flatten将3维向量拉升维1维
#全连接层的Dropout的ratio要比卷积层的要大些??
model.add(Flatten())
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10,activation='softmax'))

#训练参数配置
sgd=SGD(lr=0.01,decay=1e-6,momentum=0.9,nesterov=True)
model.compile(loss='categorical_crossentropy',optimizer=sgd)

#训练
model.fit(x_train,y_train,batch_size=31,epochs=10)

#评估模型
score = model.evaluate(x_test,y_test,batch_size=32)



你可能感兴趣的:(keras)