Keras学习~试用卷积~跑CIFAR-10

时间:2023-03-08 17:03:59
import numpy as np
import cPickle
import keras as ks
from keras.layers import Dense, Activation, Flatten, convolutional, Convolution2D, MaxPooling2D, Dropout
from keras.utils import np_utils
import logging def read_data(file):
with open(file,'rb') as fo:
dict = cPickle.load(fo)
return np.array(dict['data']).reshape(10000,32,32,3),np.array(dict['labels']).reshape(10000,1) def to4d(img):
return img.reshape(img.shape[0],3,32,32).astype(np.float32)/255 def fit(model,batch_num,val_img,val_LBL):
(train_img, train_lbl) = read_data('cifar-10/data_batch_'+str(batch_num))
train_img=to4d(train_img)
train_LBL=np_utils.to_categorical(train_lbl,nb_classes=10)
model.fit(x=train_img,y=train_LBL,batch_size=100,nb_epoch=10,verbose=1,validation_data=(val_img,val_LBL)) val_img,val_lbl = read_data('cifar-10/test_batch')
val_img = to4d(val_img)
val_LBL = np_utils.to_categorical(val_lbl,nb_classes=10) model = ks.models.Sequential()
model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=(3,32,32),dim_ordering='th'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(10))
model.add(Activation('softmax')) logging.getLogger().setLevel(logging.DEBUG) model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy']) for batch_num in range(1,6):
fit(model,batch_num,val_img,val_LBL)