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

 更新时间:2022年02月16日 17:14:13   作者:努力奋斗的K崽  
这篇文章主要介绍了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!

到此这篇关于python离散建模之感知器学习算法的文章就介绍到这了,更多相关python感知器学习算法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论