个人班级 机器学习实验-计算机18级
作业要求 实验一
姓名 程王宇
学号 3180701339

【实验目的】

  1. 理解感知器算法原理,能实现感知器算法;

  2. 掌握机器学习算法的度量指标;

  3. 掌握最小二乘法进行参数估计基本原理;

  4. 针对特定应用场景及数据,能构建感知器模型并进行预测。

【实验内容】

  1. 安装Pycharm,注册学生版。

  2. 安装常见的机器学习库,如Scipy、Numpy、Pandas、Matplotlib,sklearn等。

  3. 编程实现感知器算法。

  4. 熟悉iris数据集,并能使用感知器算法对该数据集构建模型并应用。

【实验过程及结果】

实验代码及注释

1、

import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
%matplotlib inline

2、

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)将列名设置为特征
df['label'] = iris.target增加一列为类别标签

3、

df.label.value_counts()value_counts确认数据出现的频率

4、

plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')给图加上图例
plt.ylabel('sepal width')
plt.legend()

5、

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

6、

X, y = data[:,:-1], data[:,-1]X为sepal length,sepal width y为标签

7、

y = np.array([1 if i == 1 else -1 for i in y])将两个类别设重新设置为+1 —1

8、

%# 此处为一元一次线性方程
class Model:
def init(self):将参数w1,w2置为1 b置为0 学习率为0.1
self.w = np.ones(len(data[0])-1, dtype=np.float32) data[0]为第一行的数据len(data[0]=3)这里取两个w权重参数
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):拟合训练数据求w和b
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:根据错误的样本点不断的更新和迭代w和b的值(根据相乘结果是否为负来判断是否出错,本题将0也归为错误)
self.w = self.w + self.l_ratenp.dot(y, X)
self.b = self.b + self.l_ratey
wrong_count += 1
if wrong_count == 0:直到误分类点为0 跳出循环
is_wrong = True
return 'Perceptron Model!'
def score(self):
pass

9、

perceptron = Model()
perceptron.fit(X, y)感知机模型

10、

x_points = np.linspace(4, 7,10)x轴的划分
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()

11、

from sklearn.linear_model import Perceptron定义感知机(下面将使用感知机)

12、

clf.fit(X, y)使用训练数据拟合

13、

print(clf.coef_)

14、

print(clf.intercept_)

15、

y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
plt.plot(x_ponits, 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、

2、

3、

4、

5、

6、

7、

8、

9、

10、

11、

12、

13、

14、

15、

实验小结

通过实验,初步认识了感知机的原理及应用。在一步步的代码的认识及注释过程中,加强了对编程能力的掌握。

posted on 2021-05-16 18:42  程王宇  阅读(135)  评论(0编辑  收藏  举报