1.手写数字数据集
- from sklearn.datasets import load_digits
- digits = load_digits()
from sklearn.datasets import load_digits
import numpy as np
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数据: ",X_data)
print("处理X_data后的数据空间为:",X_data.shape)
print("Y_data数据: ",Y_data)
print("处理X_data后的数据空间为:",Y_data.shape)
2.图片数据预处理
- x:归一化MinMaxScaler()
- y:独热编码OneHotEncoder()或to_categorical
- 训练集测试集划分
- 张量结构
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) #归一化MinMaxScaler() Y = OneHotEncoder().fit_transform(Y_data).todense() #独热编码OneHotEncoder() print("归一化后X_data数据: ",X_data) print("独热编码后独热编码数据: ",Y) X=X_data.reshape(-1,8,8,1) #张量结构,转换为图片的格式(batch,height,width,channels) 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,x_test,y_train,y_test)
print("输出训练集测试集的空间: ",x_train.shape,x_test.shape,y_train.shape,y_test.shape)
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')) # 一层卷积
model.add(MaxPool2D(pool_size=(2, 2))) # 池化层1
model.add(Dropout(0.25))
model.add(Conv2D(filters=32,kernel_size=(5, 5),padding='same',activation='relu')) # 二层卷积
model.add(MaxPool2D(pool_size=(2, 2))) # 池化层2
model.add(Dropout(0.25))
model.add(Conv2D(filters=64,kernel_size=(5, 5),padding='same',activation='relu')) # 三层卷积
model.add(Flatten()) # 平坦层
model.add(Dense(128, activation='relu')) # 全连接层
model.add(Dropout(0.25))
model.add(Dense(10, activation='softmax')) # 激活函数
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)
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) #batch_size为一次训练的个数,epochs为训练次数
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_true=np.array(y_test1)[0]
print("测试集空间:",y_pred.shape)
print("真实值空间:",y_true.shape)
print("预测结果(前10个):",y_pred[:10])
print("真实结果(前10个):",y_true[:10])
#交叉表查看预测数据与原数据对比
import pandas as pd
b = pd.crosstab(y_true,y_pred,rownames=['true'],colnames=['predict'])
print("交叉表:",b)
#交叉矩阵查看预测数据与原数据对比
import seaborn as sns
import matplotlib.pyplot as plt
a=pd.crosstab(np.array(y_test1),y_pred,rownames=['lables'],colnames=['predict'])
df=pd.DataFrame(a) #转换成dataframe
sns.heatmap(df,annot=True,cmap="YlGnBu",linewidths=0.2,linecolor='G')
plt.show()
ps:画图还是anaconda好!!!