zoukankan      html  css  js  c++  java
  • 实验一 感知器及其应用

    作业信息

    博客班级 计算机18级
    作业要求 实验一
    学号 3180701128

    实验目的

    1. 理解感知器算法原理,能实现感知器算法;
    2. 掌握机器学习算法的度量指标;
    3. 掌握最小二乘法进行参数估计基本原理;
    4. 针对特定应用场景及数据,能构建感知器模型并进行预测。

    实验內容

    1. 安装Pycharm,注册学生版。
    2. 安装常见的机器学习库,如Scipy、Numpy、Pandas、Matplotlib,sklearn等。
    3. 编程实现感知器算法。
    4. 熟悉iris数据集,并能使用感知器算法对该数据集构建模型并应用。

    实验报告要求

    1. 按实验内容撰写实验过程;
    2. 报告中涉及到的代码,每一行需要有详细的注释;
    3. 按自己的理解重新组织,禁止粘贴复制实验内容!

    实验代码及结果

    import pandas as pd
    import numpy as np
    from sklearn.datasets import load_iris
    import matplotlib.pyplot as plt
    %matplotlib inline
    
    # load data
    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']
    df.label.value_counts()
    

    运行结果:

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

    运行结果:

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

    运行结果:

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

    结果:

    # 截距 Constants in decision function.
    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()
    

    结果:

    实验小结

    感知机算法涉及到的学习方法、损失函数求解以及优化方法是机器学习的核心思想。也是支持向量机、神经网络等算法的基石。对感知机算法的了解能让我更容易理解在此基础上发展的更为复杂的其它算法。

  • 相关阅读:
    spring 循环依赖问题
    spring data jpa 关键字 命名
    mongodb 添加字段并设置默认值
    java mongoTemplate的group统计
    java8 从对象集合中取出某个字段的集合
    springboot12-zuul
    springboot11-01-security入门
    springboot项目怎么部署到外部tomcat
    springboot10-springcloud-eureka 服务注册与发现,负载均衡客户端(ribbon,feign)调用
    UML
  • 原文地址:https://www.cnblogs.com/hudamao/p/14774942.html
Copyright © 2011-2022 走看看