python cnn代码详解 keras_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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值