• 【感知机模型】手写代码训练 / 使用sklearn的Perceptron模块训练


    读取原始数据

    import pandas as pd
    import numpy as np
    
    in_data = pd.read_table('./origin-data/perceptron_15.dat', sep='s+', header=None)
    X_train = np.array(in_data.loc[:,[0,1,2,3]])
    y_train = np.array(in_data[4])
    

    训练感知机模型

    class MyPerceptron:
      def __init__(self):
        self.w = None
        self.b = 0
        self.l_rate = 1
    
      def fit(self, X_train, y_train):
      #用样本点的特征数更新初始w,如x1=(3,3)T,有两个特征,则self.w=[0,0]
        self.w = np.zeros(X_train.shape[1])
        i = 0
        while i < X_train.shape[0]:
          X = X_train[i]
          y = y_train[i]
          # 如果y*(wx+b)≤0 说明是误判点,更新w,b
          if y * (np.dot(self.w, X) + self.b) <= 0:
            self.w += self.l_rate * np.dot(y, X)
            self.b += self.l_rate * y
            i=0 #如果是误判点,从头进行检测
          else:
            i+=1
    
    from sklearn.linear_model import Perceptron
    
    # 使用sklearn中的Perceptron类训练
    perceptron = Perceptron()
    time1 = datetime.datetime.now()
    perceptron.fit(X_train, y_train)
    time2 = datetime.datetime.now()
    print("共用时:", (time2-time1).microseconds, "微秒")
    print(perceptron.coef_)
    print(perceptron.intercept_)
    

    共用时: 4769 微秒
    [[ 2.9686576 -1.513057 2.211151 4.227677 ]]
    [-3.]

    # 使用自己写的MyPerceptron类训练
    perceptron = MyPerceptron()
    time1 = datetime.datetime.now()
    perceptron.fit(X_train, y_train)
    time2 = datetime.datetime.now()
    print("共用时:", (time2-time1).microseconds, "微秒")
    print(perceptron.w)
    print(perceptron.b)
    

    共用时: 12479 微秒
    [ 3.6161856 -2.013502 3.123158 5.49830856]
    -4

  • 相关阅读:
    Visual Studio技巧之打造拥有自己标识的代码模板
    arcgis 10.1 错误(TCP_NODELAY NOT enabled)
    中秋节快乐
    调Windows 7的图片浏览器查看图片
    NetCFSvcUtil.exe and Windows 7
    win7下IIS错误:"无法访问请求的页面,因为该页的相关配置数据无效"的解决方法(转)
    卫星地图下载软件WebImageDowns
    出差陕西镇安
    打印完税证明
    c#定义全局条件编译符号
  • 原文地址:https://www.cnblogs.com/yanqiang/p/12038266.html
Copyright © 2020-2023  润新知