感知機程式碼

十七掌柜發表於2024-08-07
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 20:50:03 2024 @author: 田雨 """ # -*- coding: UTF-8 -*- # 匯入iris資料集 from sklearn.datasets import load_iris # 匯入資料劃分包 from sklearn.model_selection import train_test_split # 匯入感知機模型包 from sklearn.linear_model import Perceptron # 匯入基本函式庫 import matplotlib.pyplot as plt import pandas as pd import numpy as np # 定義樣本數量 global Sample_num Sample_num = 100 iris = load_iris() ## 取出iris的標籤 iris_target = iris.target iris_features = pd.DataFrame(iris.data, columns=iris.feature_names) ## 將標籤併入陣列 iris_features['target'] = iris_target iris_features.columns=['sepal length', 'sepal width', 'petal length', 'petal width', 'label'] # 取出樣本集,使用前兩個特徵 x = np.array(iris_features.iloc[:Sample_num,0:2]) y = iris_target[:Sample_num] # 切分資料集,70%訓練集,30%測試集 x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.3) # 定義感知機 pla = Perceptron( fit_intercept=False, # 不計算偏置 shuffle = False # 在每個epoch重新打亂洗牌 ) # 模型訓練 pla.fit(x_train,y_train) # 輸出權重和偏差 w = pla.coef_ b = pla.intercept_ print(f"權重(w) = {w}\n偏差(b) = {b}") # 模型測試 result = pla.score(x_test,y_test) print(f"測試結果準確率為:{result}") #—————————————————————————— 畫圖—————————————————————————————— # 分開正例反例 # 正例橫座標 positive_x = [x[i,0] for i in range(Sample_num) if y[i] == 1] # 正例縱座標 positive_y = [x[i,1] for i in range(Sample_num) if y[i] == 1] # 反例橫座標 negetive_x = [x[i,0] for i in range(Sample_num) if y[i] == 0] # 反例縱座標 negetive_y = [x[i,1] for i in range(Sample_num) if y[i] == 0] # 畫出散點圖 plt.scatter(positive_x,positive_y,c='r') plt.scatter(negetive_x,negetive_y,c='b') # 畫出超平面 line_x = np.arange(4,8) # w[0][0]x+w[0][1]y+b=0 => 斜率:-w[0][0]/w[0][1]) 截距:-b/w[0][1] line_y = line_x*(-w[0][0]/w[0][1])-b/w[0][1] plt.plot(line_x,line_y) plt.show()

相關文章