keras cnn 代码详解


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 18:00:30 2018
这是用keras搭建的简单的cnn 网络
@author: lg
"""
##

import keras
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D

from matplotlib import pyplot as plt

num_classes = 10
model_name = 'cifar10.h5'

# The data, shuffled and split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

plt.imshow(x_train[0])
plt.show()

x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255

# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()

#第一个 卷积层 的卷积核的数目是32 ,卷积核的大小是3*3,stride没写,默认应该是1*1
#对于stride=1*1,并且padding ='same',这种情况卷积后的图像shape与卷积前相同,本层后shape还是32*32
model.add(Conv2D(32, (3, 3), padding='same',strides=(1,1) ,input_shape=x_train.shape[1:]))
model.add(Activation('relu'))

#keras Pool层有个奇怪的地方,stride,默认是(2*2),padding 默认是valid,在写代码是这些参数还是最好都加上
model.add(  MaxPooling2D(pool_size=(2, 2),strides=(2,2),padding='same')  )

model.add(Dropout(0.25))


model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))

model.add(Dense(num_classes))
model.add(Activation('softmax'))

model.summary()

# initiate RMSprop optimizer
opt = keras.optimizers.rmsprop(lr=0.001, decay=1e-6)

# train the model using RMSprop
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

hist = model.fit(x_train, y_train, epochs=40, shuffle=True)
model.save(model_name)

# evaluate
loss, accuracy = model.evaluate(x_test, y_test)
print (loss, accuracy)

你可能感兴趣的:(deep,learning,with,keras)