Python实现机器学习感知机算法
导入相关库
import pandas as pd
import numpy as np
from sklearn.datasets
import load_iris
import matplotlib.pyplot as plt
导入iris数据集
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’]
绘制散点图
plt.scatter(df[:50][‘sepal length’], df[:50][‘sepal width’], c=‘red’, label=‘0’)
plt.scatter(df[50:100][‘sepal length’], df[50:100][‘sepal width’], c=‘green’, label=‘1’)
plt.xlabel(‘sepal length’)
plt.ylabel(‘sepal width’)
plt.legend();
取两列数据并将并将标签转化为1/-1
data = np.array(df.iloc[:100, [0, 1, -1]])
X, y = data[:,:-1], data[:,-1]
y = np.array([1 if i == 1 els