网络编程
位置:首页>> 网络编程>> Python编程>> python离散建模之感知器学习算法

python离散建模之感知器学习算法

作者:努力奋斗的K崽  发布时间:2022-06-10 04:49:47 

标签:python,离散,建模,感知器,学习算法

我们将研究一种判别式分类方法,其中直接学习评估 g(x)所需的 w 参数。我们将使用感知器学习算法。
感知器学习算法很容易实现,但为了节省时间,我在下面为您提供了一个实现。该函数有几个输入:训练数据、训练标签、对权重的初始猜测和学习率。注意,对于这两个类,类标签的值必须为+1和-1。

它将返回一个元组,其中包含:

  • 1.学习w参数

  • 2.执行的迭代次数

  • 3.错误分类的样本数

花些时间检查代码。如果不清楚每一行是如何工作的,不要担心,只要让你自己知道每一行的目的是什么就可以了。代码中有一些注释可以帮助大家。

def perce(X, y, w_init, rho, max_iter=1000):
    
    (N, nfeatures) = X.shape

    # Augment the feature vectors by adding a 1 to each one. (see lecture notes)
    X = np.hstack((X, np.ones((N, 1))))
    nfeatures += 1

    w = w_init  # initialise weights
    iter = 0
    mis_class = N  # start by assuming all samples are misclassified

    while mis_class > 0 and iter < max_iter:
        iter += 1
        mis_class = 0
        gradient = np.zeros(nfeatures)  # initaliase the gradients to 0

        # loop over every training sample.
        for i in range(N):
            # each misclassified point will cause the gradient to change
            if np.inner(X[i, :], w) * y[i] <= 0:
                mis_class += 1
                gradient += -y[i] * X[i, :]
        # update the weight vector ready for the next iteration
        # Note, also that the learning rate decays over time (rho/iter)
        w -= rho / iter * gradient

    return w, iter, mis_class

解释:

X-数据矩阵。每行代表一个单独的样本
y-与X-标签行对应的整数类标签的一维数组必须为+1或-1
w_init-初始权重向量
rho-标量学习率
最大迭代次数-最大迭代次数(默认为1000)

def perce_fast(X, y, w_init, rho, max_iter=10000):
  
    (N, nfeatures) = X.shape
    X = np.hstack((X, np.ones((N, 1))))
    nfeatures += 1
    w = w_init
    iter = 0
    mis_class = N
    yy = np.tile(y, (nfeatures, 1)).T
    while mis_class > 0 and iter < max_iter:
        iter += 1
        # Compute set of misclassified points
        mc = (np.dot(X, w.transpose()) * y) <= 0
        mis_class = np.sum(mc)
        # Update weights. Note, the learning rate decays over time (rho/iter)
        w -= rho / iter * (np.sum(-yy[mc, :] * X[mc, :], axis=0))
    return w, iter, np.sum(mc)
  • 感知器算法的高效实现

  • 对于笔记本电脑数据,此版本的工作速度将提高x100!

来源:https://blog.csdn.net/kirsten111111/article/details/121429528

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com