15 手写数字识别-小数据集

1.手写数字数据集

  • from sklearn.datasets import load_digits
  • digits = load_digits()

 

from sklearn.datasets import load_digits
digits = load_digits()

2.图片数据预处理

  • x:归一化MinMaxScaler()
  • y:独热编码OneHotEncoder()或to_categorical
  • 训练集测试集划分
  • 张量结构

 代码:

X_data = digits.data.astype(np.float32)
scale = MinMaxScaler()
X_data = scale.fit_transform(X_data)    #归一化
X = X_data.reshape(-1,8,8,1)

Y_data = digits.target.astype(np.float32).reshape(-1,1)
Y = OneHotEncoder().fit_transform(Y_data).todense() #热独编码

X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.2,random_state=0,stratify=Y)
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)

结果:

 

 

 

3.设计卷积神经网络结构

  • 绘制模型结构图,并说明设计依据。

代码:

# 建立模型
model = Sequential()

# 一层卷积
model.add(
     Conv2D(
         filters=16, # 卷积核种类
         kernel_size=(3, 3),    # 卷积核大小
         padding='same',
         input_shape=X_train.shape[1:],
         activation='relu'))
# 池化层1
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))    # 随机丢弃1/4,防止过拟合

# 二层卷积
model.add(
     Conv2D(
         filters=32,
         kernel_size=(3, 3),
         padding='same',
         activation='relu'))
# 池化层2
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

# 三层卷积
model.add(
     Conv2D(
         filters=64,
         kernel_size=(3, 3),
         padding='same',
         activation='relu'))
# 四层卷积
model.add(
     Conv2D(
         filters=128,
         kernel_size=(3, 3),
         padding='same',
         activation='relu'))
# 池化层3
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())  # 平坦层
model.add(Dense(128, activation='relu'))  # 全连接层
model.add(Dropout(0.25))
model.add(Dense(10, activation='softmax')) # 激活函数
model.summary()

结果:

15 手写数字识别-小数据集_第1张图片

 

 

 设计说明:

15 手写数字识别-小数据集_第2张图片

4.模型训练

  • model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
  • train_history = model.fit(x=X_train,y=y_train,validation_split=0.2, batch_size=300,epochs=10,verbose=2)

代码:

# 训练模型
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
train_history = model.fit(x=X_train,
                          y=y_train,
                          validation_split=0.2,
                          batch_size=256,
                          epochs=80,
                          verbose=2)

结果:

15 手写数字识别-小数据集_第3张图片

5.模型评价

  • model.evaluate()
  • 交叉表与交叉矩阵
  • pandas.crosstab
  • seaborn.heatmap

代码:

# 模型评价
score = model.evaluate(X_test,y_test)
print(score)
# 预测值
y_pred = model.predict_classes(X_test)
y_test1 = np.argmax(y_test, axis=1).reshape(-1)
y_test2 = np.array(y_test1)[0]
# 交叉表
import pandas as pd
pd.crosstab(y_test2,y_pred,rownames=['labels'],colnames=['predict'])

# 交叉矩阵
import seaborn as sns
import pandas as pd
y_test1 = y_test1.tolist()[0]
a = pd.crosstab(np.array(y_test1), y_pred, rownames=['Lables'], colnames=['Predict'])
# 转换成属dataframe
df = pd.DataFrame(a)
sns.heatmap(df, annot=True, cmap="YlGn", linewidths=0.2, linecolor='G')
plt.show()

结果:

15 手写数字识别-小数据集_第4张图片

 

 15 手写数字识别-小数据集_第5张图片

你可能感兴趣的:(15 手写数字识别-小数据集)