实验一 感知器及其应用

【个人信息】

实验班级 https://edu.cnblogs.com/campus/ahgc/machinelearning/homework/11950
实验要求 https://edu.cnblogs.com/campus/ahgc/machinelearning/homework/11950
学号 3180701317
姓名 李家辉
【实验目的】
  1. 理解感知器算法原理,能实现感知器算法;

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

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

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

【实验内容】

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

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

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

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

【实验报告要求]

  1. 按实验内容撰写实验过程;

  2. 报告中涉及到的代码,每一行需要有详细的注释;

  3. 按自己的理解重新组织,禁止粘贴复制实验内容!
    【实验代码】
    1、

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

2

# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target

3

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

4

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.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()

5

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])

6

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

7

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()
from sklearn.linear_model import Perceptron
clf = Perceptron(fit_intercept=False, max_iter=1000, shuffle=False)
clf.fit(X, y)
# Weights assigned to the features.
print(clf.coef_)
print(clf.intercept_)

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.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()

【实验结果】




【实验小结】
感知器是人工神经网络中的一种典型结构, 它的主要的特点是结构简单。它是一种分类学习器,是很多复杂算法的基础。其“赏罚概念”在机器学习算法在中广为应用。在分类正确时,对正确的权重向量w赏,即w不变;当分类错误时,对权重向量罚,即将权重向量w向着争取的方向转变。

posted @ 2021-05-18 12:18  李家辉  阅读(72)  评论(0编辑  收藏  举报