手写数字识别算法
多层感知器预测例子
import pandas as pd
import numpy as np
from sklearn.neural_network import MLPRegressor
data_tr = pd.read_csv('BPdata_tr.txt')
data_te = pd.read_csv('BPdata_te.txt')
X=np.array([[0.568928884039633],[0.379569493792951]]).reshape(1, -1)
model = MLPRegressor(hidden_layer_sizes=(10,), activation='relu',random_state=10, max_iter=8000, learning_rate_init=0.3)
model.fit(data_tr.iloc[:, :2], data_tr.iloc[:, 2])
pre = model.predict(data_te.iloc[:, :2])
pre1 = model.predict(X)
err = np.abs(pre - data_te.iloc[:, 2]).mean()
print("模型预测值:",pre,end='\n______________________________\n')
print('模型预测误差:',err,end='\n++++++++++++++++++++++++++++++++\n')
print("单个样本预测值:",pre1,end='\n++++++++++++++++++++++++++++++++\n')
print('权重矩阵:','\n',model.coefs_)
print('偏置矩阵:','\n',model.intercepts_)
数字手写识别系统
import numpy as np
from os import listdir
from sklearn.neural_network import MLPClassifier
def img2vector(fileName):
retMat = np.zeros([1024], int)
fr = open(fileName)
lines = fr.readlines()
for i in range(32):
for j in range(32):
retMat[i * 32 + j] = lines[i][j]
return retMat
def readDataSet(path):
fileList = listdir(path)
numFiles = len(fileList)
dataSet = np.zeros([numFiles, 1024], int)
hwLabels = np.zeros([numFiles, 10])
for i in range(numFiles):
filePath = fileList[i]
digit = int(filePath.split('_')[0])
hwLabels[i][digit] = 1.0
dataSet[i] = img2vector(path + '/' + filePath)
return dataSet, hwLabels
train_dataSet, train_hwLabels = readDataSet('trainingDigits')
clf = MLPClassifier(hidden_layer_sizes=(50,),activation='logistic', solver='adam',learning_rate_init=0.001, max_iter=700)
clf.fit(train_dataSet, train_hwLabels)
dataSet, hwLabels = readDataSet('testDigits')
res = clf.predict(dataSet)
print("测试数据",dataSet,'\n___________________________________\n')
print("测试标签",hwLabels,'\n++++++++++++++++++++++++++++++++++++++++\n')
print("测试结果",res)
error_num = 0
num = len(dataSet)
for i in range(num):
if np.sum(res[i] == hwLabels[i]) < 10:
error_num += 1
print("Total num:", num, " Wrong num:",error_num, " WrongRate:", error_num / float(num))
可视化MNIST是数字手写识别的数据集
from keras.datasets import mnist
import matplotlib.pyplot as plt
(X_train, y_train), (X_test, y_test) = mnist.load_data()
plt.subplot(221)
plt.imshow(X_train[1], cmap=plt.get_cmap('gray_r'))
plt.subplot(222)
plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(X_train[4], cmap=plt.get_cmap('gray'))
plt.show()