这篇文章主要介绍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)
以上是“python如何实现感知器学习算法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。