Perceptron

perceptron

math method

perceptron model

\(f(x)=sign(wx+b)\)通过输入的datasets进行二分类的线性模型。

perceptron learning strategy

直观:分类错误的点->数学描述:误分类的点到超平面的距离\(-\frac{y_i(wx_i+b)}{||w||}\)又由于在同一空间类\(||w||\)对整个分类过程不产生分类影响。Loss Function=经验风险函数:\(L_{(w,b)}=-\sum_{x_i \in M}y_i(wx_i+b)\)

Algorithm

主要是得到一个最小的Loss结果:\(min_{w,b}L_{(w,b)}=-min\sum_{x_i \in M}y_i(wx_i+b)\)在这个实现过程中采用随机梯度下降法。

  • Stochastic Gradient Descent

    \(w=w+\eta y_ix_i\)在整个迭代过程中\(\eta\)是作为Learning Rate,整个过程不断迭代untill 最小误差

    \(b=b+\eta y_i\)

Dual Form

对偶形式的差别主要在迭代方式上,

\(w=\sum_{i=1}^Ma_iy_ix_i\)由此产生的\(f(x)=sign(\sum_{j=1}^Ma_jy_jx_jx_i+b)\)的对偶形式。

\(b=\sum_{i=1}^Ma_iy_i\)由上式构建\(G=[\vec x_i.\vec x_j]_{N*N}\)的矩阵来减小运算量

\(a_i=a_i+\eta\)迭代

\(b=b+\eta y_i\)

Code Test

数据导入

# load data
iris = load_iris()#自带的鸢尾花数据
df = pd.DataFrame(iris.data, columns=iris.feature_names)#数据帧
df['label'] = iris.target#种类标签
df.label.value_counts()#3种花,每种50

.columns和.index是返回数据集的列索引和行索引

df.columns = [ 'sepal length', 'sepal width', 'petal length', 'petal width', 'label' ]#隔片长度,隔片宽度,花瓣长度,花瓣宽度,花种类,在这里明确了行索引,由标签值知道了数据分布

绘图

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]])#iloc函数根据索引位选取数据
X, y = data[:,:-1], data[:,-1]#所有数据,直到最后一个元素,最后一个元素
y = np.array([1 if i == 1 else -1 for i in y])#sign function

在整个过程中[:100,[0,1,-1]]表示的意思是选取illoc数据中的前100行,第一、二,以及最后一列的数据。然后再通过第二行的代码对数据进行分割。第3行中类似

for i in y:
    if i == 1:
        y=1
    else:
        y=-1

构建模型

# 数据线性可分,二分类数据
# 此处为一元一次线性方程
class Model:
    def __init__(self):
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        #由数据处理代码可知data中有3个元素,所以np.ones(2)生成一个指定大小和类型的数组
        self.b = 0
        self.l_rate = 0.1#学习率
        # self.data = data

    def sign(self, x, w, b):
        y = np.dot(x, w) + b#线性方程
        #np.dot是x,w两个数组相乘
        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)):#遍历train sets
                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:#untill 错误次数为0
                is_wrong = True
        return 'Perceptron Model!'

    def score(self):
        pass

perceptron = Model()#调用建立模型 perceptron.fit(X, y)#感知机regression

将三维空间转化为二维显示

x_points = np.linspace(4, 7, 10)#4 to 7描10个点
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
#原本是一个面分割的
plt.plot(x_points,y_,c='r')
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()

在第二行的代码

\[X=(x_1,x_2) \ W=(w_1,w_2)\\f(X)=signWX+b=sign(w_1x_1+w_2x_2+b)
\]

将上式作为分界,在二维面上的显示

\[w_1x_1+w_2x_2+b=0 \\ x_2=- \frac {w_1x_1+b}{w_2}
\]

![](C:\Users\Tian\Desktop\博客\Pictures\Screenshot from 2020-07-06 22-27-13.png)

scikit-learn实例

初始化

import sklearn
from sklearn.linear_model import Perceptron#导入感知机线性模型
sklearn.__version__

clf = Perceptron(fit_intercept=True, #拦截
                 max_iter=1000,#最大训练次数
                 tol=None,#default=1e-3,拟合
                 shuffle=True)#每次训练后重新洗牌数据
clf.fit(X, y)#Stochstic Gradient Dsecent进行拟合--SGD

参量

# 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.legend()  # 显示图例
plt.grid(False)  # 不显示网格
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()

版权声明:本文为TCD-record原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/TCD-record/p/13260395.html