1.手写数字数据集
- from sklearn.datasets import load_digits
- digits = load_digits()
代码如下:
from sklearn.datasets import load_digits import numpy as np # 1.手写数字数据集 digits = load_digits() X_data = digits.data.astype(np.float32) Y_data = digits.target.astype(np.float32).reshape(-1, 1) # 将Y_data变为一列 print("X_data:\n", X_data, "\nY_data:\n", Y_data)
运行结果图如下:
2.图片数据预处理
- x:归一化MinMaxScaler()
- y:独热编码OneHotEncoder()或to_categorical
- 训练集测试集划分
- 张量结构
代码如下:
# 2.图片数据预处理 # 1)归一化 from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split scaler = MinMaxScaler() X_data = scaler.fit_transform(X_data) print('MinMaxScaler_trans_X_data:') print(X_data) # 2)独热编码 Y = OneHotEncoder().fit_transform(Y_data).todense() # one-hot编码 print('OneHot_Y:') print(Y) # 3)划分训练集测试集 X = X_data.reshape(-1, 8, 8, 1) # 张量结构 X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0, stratify=Y) print("X.shape:\n", X.shape, "\nX_train.shape:\n", X_train.shape, "\nX_test.shape:\n", X_test.shape, "\nY_train.shape:\n", Y_train.shape, "\nY_test.shape:\n", Y_test.shape)
运行结果图如下:
3.设计卷积神经网络结构
- 绘制模型结构图,并说明设计依据。
代码如下:
# 3.设计卷积神经网络结构 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D # 建立模型 model = Sequential() # 一层卷积 model.add(Conv2D(filters=16, kernel_size=(5, 5), padding='same', input_shape=X_train.shape[1:], activation='relu')) # 池化层1 model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) # 二层卷积 model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='same', activation='relu')) # 池化层2 model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) # 三层卷积 model.add(Conv2D(filters=64, kernel_size=(5, 5), padding='same', activation='relu')) # 四层卷积 model.add(Conv2D(filters=128, kernel_size=(5, 5), 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')) print("变化过程:\n") model.summary()
运行结果图如下:
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)
代码如下:
# 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=55, verbose=2)
运行结果图如下:
5.模型评价
- model.evaluate()
- 交叉表与交叉矩阵
- pandas.crosstab
- seaborn.heatmap
代码如下:
# 5.模型评价 import pandas as pd import seaborn as sns import matplotlib.pyplot as plt score = model.evaluate(X_test, Y_test) print(score) # 交叉表与交叉矩阵 # 1)预测值 y_pred = model.predict_classes(X_test) print(y_pred[:10]) # 2)交叉表查看预测数据与元数据对比 y_test1 = np.argmax(Y_test, axis=1).reshape(-1) y_true = np.array(y_test1)[0] print(y_test1) pd.crosstab(y_true, y_pred, rownames=["true"], colnames=["predict"]) # 3)交叉矩阵 a = pd.crosstab(np.array(y_test1).reshape(-1), y_pred) df = pd.DataFrame(a) sns.heatmap(df, annot=True, cmap='summer', linewidths=0.2, linecolor='G') plt.show()
运行结果图如下: