import struct
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten
from keras.layers import Conv2D,MaxPooling2D
from keras import backend
import os
import numpy as np
def load_mnist(path,kind="train"):
labels_path=os.path.join(path, '%s-labels-idx1-ubyte' % kind)
images_path=os.path.join(path, '%s-images-idx3-ubyte' % kind)
with open(labels_path,'rb') as lbpath:
magic, n = struct.unpack('>II', lbpath.read(8))
labels = np.fromfile(lbpath, dtype=np.uint8)
with open(images_path, 'rb') as imgpath:
magic, num, rows, cols = struct.unpack(">IIII", imgpath.read(16))
images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)
# Construct an array from data in a text or binary file.
return images, labels
path=".\data"
X_train, y_train =load_mnist(path , kind='train')
print('Rows:%d,columns:%d' % (X_train.shape[0], X_train.shape[1]))
X_test, y_test = load_mnist(path, kind='t10k')
print('Rows:%d,columns:%d' % (X_test.shape[0], X_test.shape[1]))
print(type(X_train)) #<class 'numpy.ndarray'>
print(y_train)#[5 0 4 ... 5 6 8]
print(y_train.shape)#60000,
batch_size=128
num_classes=10
epochs=1
'''
def image_data_format():
"""Returns the default image data format convention ('channels_first' or 'channels_last').
# Returns
A string, either `'channels_first'` or `'channels_last'`
'''
if backend.image_data_format()=='channels_first':
X_train=X_train.reshape(X_train.shape[0],1,28,28)
X_test=X_test.reshape(X_test.shape[0],1,28,28)
input_shape=(1,28,28)
else:
X_train = X_train.reshape(X_train.shape[0], 28, 28,1)
X_test = X_test.reshape(X_test.shape[0], 28, 28,1)
input_shape=(28,28,1)
X_train=X_train.astype('float32')
X_test=X_test.astype('float32')
# TypeError: No loop matching the specified signature and casting
# was found for ufunc true_divide()
#防止下面两条出错
X_train /=255
X_test /=255
print('x_train shape',X_train.shape)
#(60000, 28, 28, 1)
#convert class vectors to binary class matrices
#one hot编码
import keras
y_train=keras.utils.to_categorical(y_train,num_classes)
y_test=keras.utils.to_categorical(y_test,num_classes)
print(y_train.shape) #(60000, 10)
print(y_train[0]) #[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
model=Sequential()
#[3*3*32]
#(60000, 28, 28, 1)->(60000, 26, 26, 32)
model.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=input_shape,padding="valid",strides=(1,1)))
#(60000, 26, 26, 32)->(60000, 24, 24, 64)
model.add(Conv2D(64,kernel_size=(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
#(60000, 24, 24, 64)->(60000, 12, 12, 64)
model.add(Dropout(0.25))#防止过拟合
model.add(Flatten())
#(60000, 12, 12, 64)->(60000, 12*12* 64)
"""
model = Sequential()
model.add(Conv2D(64, (3, 3),
input_shape=(3, 32, 32), padding='same', ))
# now: model.output_shape == (None, 64, 32, 32)
model.add(Flatten())
# now: model.output_shape == (None, 65536)
"""
model.add(Dense(units=128,activation='relu'))
#`Dense` implements the operation:
#`output = activation(dot(input, kernel) + bias)`
#(60000, 12*12* 64)->(60000, 128)
model.add(Dropout(0.5))
model.add(Dense(units=num_classes,activation="softmax"))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])
print(model)
model.fit(x=X_train,y=y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(X_test,y_test))
score=model.evaluate(x=X_test,y=y_test,verbose=0)
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches."""
print("Test Loss:",score[0])
print("Test accuracy:",score[1])
#模型保存
model.save("mnist.model")
print()
Karas MNISt数据集识别
最新推荐文章于 2022-12-09 15:46:21 发布