#关于线性模型:y'=w[0]*x[0]+w[0]*x[0]+...+w[p]*x[p]+b,其中,y'表示对y的估算值,x[0]到x[p]是样本特征值,w表示每个特征值的权重,
# y'可以看成是所有特征值的加权求和。基本原理是找到当训练数据集中y的预测值和其真实值的平方差最小的时候,所对应的w值和b值。
#非线性矫正:生成隐藏层之后,需要对结果进行非线性矫正(relu)或双曲正切处理(tanh),通过这两种方式处理后的结果用来计算最终结果y。
#MLP计算流程:
#1、y0=w[0]*x[0]+w[0]*x[0]+...+w[p]*x[p]+b、y1=w[0]*x[0]+w[0]*x[0]+...+w[p]*x[p]+b、y2=w[0]*x[0]+w[0]*x[0]+...+w[p]*x[p]+b
#2、h0=tanh(y0)、h1=tanh(y1)、h2=tanh(y2)
#3、y'=v[0]*h0+v[1]*h1+...+v[n]*hn
#导入MLP神经网络
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
#导入数据集获取工具
from sklearn.datasets import fetch_mldata
from PIL import Image
def mlp_wine():
wine=load_wine()
x=wine.get('data')[:,:2]
y=wine.get('target')
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0)
#定义分类器,两个节点数为10的隐藏层,tanh为激活函数
mlp=MLPClassifier(solver='lbfgs',hidden_layer_sizes=10,activation='tanh',alpha=1)
mlp.fit(x_train,y_train)
#使用不同色块表示不同分类
cmap_light=ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold=ListedColormap(['#FF0000','#00FF00','#0000FF'])
x_min,x_max=x_train[:,0].min()-1,x_train[:,0].max()+1
y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1
xx,yy=np.meshgrid(np.arange(x_min,x_max,.02),np.arange(y_min,y_max,.02))
z=mlp.predict(np.c_[xx.ravel(),yy.ravel()])
z=z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,yy,z,cmap=cmap_light)
#将数据特征用散点图表示出来
plt.scatter(x[:,0],x[:,1],c=y,edgecolors='k',s=60)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
#设定图标题
plt.title("MLPClassifier:solver=lbfgs")
plt.show()
def mlp_mnist():
#加载mnist手写数字数据集
mnist=fetch_mldata('MNIST original',data_home='./')
x=mnist.get('data')/255.
y=mnist.get('target')
x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=5000,test_size=1000,random_state=62)
#设置神经网络有两个100个节点的隐藏层
mlp_hw=MLPClassifier(solver='lbfgs',hidden_layer_sizes=[100,100],activation='relu',alpha=1e-5,random_state=62)
mlp_hw.fit(x_train,y_train)
print("训练数据集得分:{:.2f}%".format(mlp_hw.score(x_train, y_train) * 100))
print("测试数据集得分:{:.2f}%".format(mlp_hw.score(x_test,y_test)*100))
#打开图像
image=Image.open('./mldata/4.png').convert('F')
#调整图像的大小
image=image.resize((28,28))
arr=[]
#将图像中的像素作为预测数据点的特征
for i in range(28):
for j in range(28):
pixel=1.0-float(image.getpixel((j,i)))/255.
arr.append(pixel)
#由于只有一个样本,所以需要进行reshape操作
arr1=np.array(arr).reshape(1,-1)
print("图片中的数字是:{0:.0f}".format(mlp_hw.predict(arr1)[0]))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)