"""基于numpy的一种工具,为了解决数据分析任务而创建的
高效操作大型数据集"""
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from sklearn.linear_model import Perceptron
"""sklearn自带的数据集"""
"""鸢尾花数据集"""
iris = load_iris()
"""iris.data(获取属性数据),iris.feature_names(获取列属性值)"""
df = pd.DataFrame(iris.data, columns=iris.feature_names)
# print(df)
"""获取类别数据,这里注意的是已经经过处理,targe里0、1、2分别代表三种类别"""
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', color='blue')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1', color='orange')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()
data = np.array(df.iloc[:100, [0, 1, -1]])
# print(data)
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
def sign(self, X, w, b):
"""dot()返回的是两个数组的点积"""
Y = np.dot(X, w) + b
return Y
"""随机梯度下降法 """
"""实现书P29,算法2.1--感知机学习算法"""
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)
"""4-7中生成10个等差数据"""
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
"""x轴数据为x_points,y轴数据为y_"""
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()
plt.show()
-
从sklearn.linear_model中调用Perceptron以实现感知机问题
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])
"""自定义感知机"""
clf = Perceptron(fit_intercept=False, n_iter=1000, shuffle=False)
"""使用训练数据进行训练"""
clf.fit(x, y)
"""得到训练结果,权重矩阵"""
print(clf.coef_)
"""超平面的截距,此处输出W为:[0.]"""
print(clf.intercept_)
x_points = np.arange(4, 8)
y_ = -(clf.coef_[0][0] * x_points + clf.intercept_) / clf.coef_[0][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()
plt.show()