【机器学习】感知机实现鸢尾花数据集实例

感知机是二类分类的线性分类模型,其输入为实例的特征向量,输出为实例的类别,取+1和-1二值。

 

感知机的线性方程:    w*x+b=0

运用鸢尾花数据集

#导入库函数
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt


# load data 下载数据集
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
#标签赋给label
df['label'] = iris.target

df.columns = [
    'sepal length', 'sepal width', 'petal length', 'petal width', 'label'
]

df.label.value_counts()
#location 定位前100行 
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
        #步长 rate
        self.l_rate = 0.1
        # self.data = data
    
    #误分类 判别
    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.l_rate * np.dot(y, X)
                    self.b = self.b + self.l_rate * y
                    wrong_count += 1
            if wrong_count == 0:
                is_wrong = True
        return 'Perceptron Model!'

    def score(self):
        pass
    
perceptron = Model()
perceptron.fit(X, y)



x_points = np.linspace(4, 7, 10)
#绘制曲线
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.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()

【机器学习】感知机实现鸢尾花数据集实例_第1张图片

《统计学习方法》P40页 例2.1

正实例点(3,3)(4,3)负实例点(1,1)

import pandas as pd
import numpy as np
#from sklearn.datasets import load_iris
import matplotlib.pyplot as plt


# load data
iris.data=np.array([
    [4,3],
    [3,3],
    [1,1]  
])

iris.target=[1,0,-1]
#iris.feature_names = ['a','b','c']

df = pd.DataFrame(iris.data, columns=['a','b'])
df['label'] = iris.target

df.columns = [
    'sepal length', 'sepal width',  'label'
]
df.label.value_counts()

data = np.array(df.iloc[:3, [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.l_rate = 0.1
        # self.data = data

    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.l_rate * np.dot(y, X)
                    self.b = self.b + self.l_rate * y
                    wrong_count += 1
            if wrong_count == 0:
                is_wrong = True
        return 'Perceptron Model!'

    def score(self):
        pass
    
perceptron = Model()
perceptron.fit(X, y)



x_points = np.linspace(0, 5, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.plot(x_points, y_)

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

#第二个分类点 = 变色
plt.plot(data[0:1, 0], data[0:1, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()

你可能感兴趣的:(机器学习,人工智能,python)