機器學習演算法實現(1) 感知機

2021-10-08 03:42:03 字數 2965 閱讀 4574

演算法實現

import pandas as pd

import numpy as np

from sklearn.datasets import load_iris

import matplotlib.pyplot as plt

iris = load_iris()

df = pd.dataframe(iris.data,columns=iris.feature_names)

df['label'] = iris.target

df.columns = [ 'sepal length', 'sepal width',

'petal length', 'petal width', 'label']

df.label.value_counts()

plt.scatter(df[:50]['sepal length'],df[:50]['sepal width'],label='0')

plt.scatter(df[50:100]['sepal length'],df[50:100]['sepal width'],label='1')

plt.legend()

data=np.array(df.iloc[:100,[0,1,-1]])

x, y = data[:,:-1], data[:,-1]

y = np.array([1 if i == 1 else -1 for i in y])

class model:

def __init__(self):

self.w=np.ones(len(data[0])-1,dtype=np.float32)

self.b=0

self.lr=0.1

def sign(self,x,w,b):

y = np.dot(x,w)+b

return y

def fit(self,x_train,y_train):

is_wrong=false

while not is_wrong:

wrong_count = 0

for d in range(len(x_train)):

x = x_train[d]

y = y_train[d]

if y*(self.sign(x,self.w,self.b))<=0:

self.w = self.w+self.lr*np.dot(y,x)

self.b = self.b+self.lr*y

wrong_count+=1

if wrong_count==0:

is_wrong=true

print("都分類正確了,w引數為:",self.w)

def score(self):

pass

mode = model()

mode.fit(x, y )

x_points = np.linspace(4, 7, 10)

print(x_points)

print(mode.w)

y_ = (mode.w[0] * x_points + mode.b)/(-mode.w[1])

plt.plot(x_points, y_)

plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')

plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')

plt.xlabel('sepal length')

plt.ylabel('sepal width')

plt.legend()

sklearn實現

import sklearn

from sklearn.linear_model import perceptron

clf = perceptron(fit_intercept=true,

max_iter=1000,

tol=none,

shuffle=true)

clf.fit(x, y)

# 畫布大小

plt.figure(figsize=(10,10))

# 中文標題

plt.rcparams['font.sans-serif']=['simhei']

plt.rcparams['axes.unicode_minus'] = false

plt.title('鳶尾花線性資料示例')

plt.scatter(data[:50, 0], data[:50, 1], c='b', label='iris-setosa',)

plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='iris-versicolor')

# 畫感知機的線

x_ponits = np.arange(4, 8)

y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]

plt.plot(x_ponits, y_)

# 其他部分

plt.legend() # 顯示圖例

plt.grid(false) # 不顯示網格

plt.xlabel('sepal length')

plt.ylabel('sepal width')

plt.legend()

機器學習 感知機演算法

感知機 perception 是一種二類線性模型,主要用於分類問題。目標函式 f x sgn w x b 其中sgn為符號函式 其中向量w為目標函式向量,向量x為樣本。向量w 向量x 超平面 w x b 0 所構成的平面 向量w為超平面上的法向量。訓練集 t x1,y1 x2,y2 x3,y3 xn...

機器學習演算法 感知機

今天把感知機的演算法用python實現了一下。主要依據的演算法流程是 統計學習方法 中關於感知機的演算法過程,具體如下。隨機生成訓練資料,測試資料也可同樣方法生成 m 樣本的個數 n 每個樣本具有的特徵維數 y 1 x np.random.random m,n x2 np.random.random...

機器學習 感知機模型(pocket演算法)實現

這裡使用pocket演算法 pocket演算法的思想非常簡單,在搜尋w的時候,不斷記錄最好的準確率和w。這樣即使資料不是線性可分的,也可以得到比較好的測試結果 只要不斷的提高迭代的次數 資料 計算準確率函式 計算錯誤率 def checkerrorrate testmatdata,testlabel...