吳裕雄 python 機器學習——人工神經網絡感知機學習算法
阿新 • • 發佈:2019-05-01
感知 matplot subplot dom 評價 mark arange data turn
import numpy as np from matplotlib import pyplot as plt from sklearn.neural_network import MLPClassifier def creat_data_no_linear_2d(n): ‘‘‘ 創建二維的線性不可分數據集 :param n: 負例的數量 :return: 線性不可分數據集,數據集大小為 2*n+n/10 ( n/10 是誤差點的數量,誤差點導致了線性不可分) ‘‘‘ np.random.seed(1) x_11=np.random.randint(0,100,(n,1)) # 第一組:第一維坐標值 x_12=10+np.random.randint(-5,5,(n,1,))# 第一組:第二維坐標值 x_21=np.random.randint(0,100,(n,1))# 第二組:第一維坐標值 x_22=20+np.random.randint(0,10,(n,1))# 第二組:第二維坐標值 x_31=np.random.randint(0,100,(int(n/10),1))# 第三組:第一維坐標值 x_32=20+np.random.randint(0,10,(int(n/10),1))#第三組:第二維坐標值 new_x_11=x_11*np.sqrt(2)/2-x_12*np.sqrt(2)/2## 沿第一維軸旋轉45度 new_x_12=x_11*np.sqrt(2)/2+x_12*np.sqrt(2)/2## 沿第一維軸旋轉45度 new_x_21=x_21*np.sqrt(2)/2-x_22*np.sqrt(2)/2## 沿第一維軸旋轉45度 new_x_22=x_21*np.sqrt(2)/2+x_22*np.sqrt(2)/2## 沿第一維軸旋轉45度 new_x_31=x_31*np.sqrt(2)/2-x_32*np.sqrt(2)/2## 沿第一維軸旋轉45度 new_x_32=x_31*np.sqrt(2)/2+x_32*np.sqrt(2)/2## 沿第一維軸旋轉45度 plus_samples=np.hstack([new_x_11,new_x_12,np.ones((n,1))]) # 拼接成正例數據集 minus_samples=np.hstack([new_x_21,new_x_22,-np.ones((n,1))])# 拼接成負例數據集 err_samples=np.hstack([new_x_31,new_x_32,np.ones((int(n/10),1))])# 拼接成正例數據集,它導致了線性不可分 samples=np.vstack([plus_samples,minus_samples,err_samples]) # 拼接成數據集 np.random.shuffle(samples) # 混洗數據 return samples def plot_samples_2d(ax,samples): ‘‘‘ 繪制二維數據集 :param ax: Axes 實例,用於繪制圖形 :param samples: 二維數據集 :return: None ‘‘‘ Y=samples[:,-1] position_p=Y==1 ## 正類位置 position_m=Y==-1 ## 負類位置 ax.scatter(samples[position_p,0],samples[position_p,1],marker=‘+‘,label=‘+‘,color=‘b‘) ax.scatter(samples[position_m,0],samples[position_m,1],marker=‘^‘,label=‘-‘,color=‘y‘) def run_plot_samples_2d(): ‘‘‘ 繪制二維線性不可分數據集 :return: None ‘‘‘ fig=plt.figure() ax=fig.add_subplot(1,1,1) data=creat_data_no_linear_2d(100) # 生成二維線性不可分數據集 plot_samples_2d(ax,data) ax.legend(loc=‘best‘) plt.show() run_plot_samples_2d()
def predict_with_MLPClassifier(ax,train_data): ‘‘‘ 使用 MLPClassifier繪制預測結果 :param ax: Axes 實例,用於繪制圖形 :param train_data: 訓練數據集 :return: None ‘‘‘ train_x=train_data[:,:-1] train_y=train_data[:,-1] clf=MLPClassifier(activation=‘logistic‘,max_iter=1000)# 構造分類器實例 clf.fit(train_x,train_y) # 訓練分類器 print(clf.score(train_x,train_y)) # 查看在訓練集上的評價預測精度 ## 用訓練好的訓練集預測平面上每一點的輸出## x_min, x_max = train_x[:, 0].min() - 1, train_x[:, 0].max() + 2 y_min, y_max = train_x[:, 1].min() - 1, train_x[:, 1].max() + 2 plot_step=1 xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),np.arange(y_min, y_max, plot_step)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) ax.contourf(xx, yy, Z, cmap=plt.cm.Paired) def run_predict_with_MLPClassifier(): ‘‘‘ 用 MLPClassifier 預測線性不可分數據集 :return: None ‘‘‘ data=creat_data_no_linear_2d(500) #生成線性不可分數據集 fig=plt.figure() ax=fig.add_subplot(1,1,1) predict_with_MLPClassifier(ax,data) plot_samples_2d(ax,data) ax.legend(loc=‘best‘) plt.show() run_predict_with_MLPClassifier()
吳裕雄 python 機器學習——人工神經網絡感知機學習算法