- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在努力学习 Daume 的书
http://ciml.info/dl/v0_99/ciml-v0_99-ch04.pdf (第 43 页)。
使用 numpy 和不使用 python 在 python 中拟合普通感知器模型使用 sciki-learn 库。
书上给出了算法
我们如何在实践中实现该模型?
到目前为止,我已经学会了如何读取数据和标签:
def read_data(infile):
data = np.loadtxt(infile)
X = data[:,:-1]
Y = data[:,-1]
return X, Y
我们将不胜感激!!
最佳答案
我想到的一种方法是:
(随时欢迎更好的想法!!)
#!python
# -*- coding: utf-8 -*-#
"""
Perceptron Algorithm.
@author: Bhishan Poudel
@date: Oct 31, 2017
"""
# Imports
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm
import os, shutil
np.random.seed(100)
def read_data(infile):
data = np.loadtxt(infile)
X = data[:,:-1]
Y = data[:,-1]
return X, Y
def plot_boundary(X,Y,w,epoch):
try:
plt.style.use('seaborn-darkgrid')
# plt.style.use('ggplot')
#plt.style.available
except:
pass
# Get data for two classes
idxN = np.where(np.array(Y)==-1)
idxP = np.where(np.array(Y)==1)
XN = X[idxN]
XP = X[idxP]
# plot two classes
plt.scatter(XN[:,0],XN[:,1],c='b', marker='_', label="Negative class")
plt.scatter(XP[:,0],XP[:,1],c='r', marker='+', label="Positive class")
# plt.plot(XN[:,0],XN[:,1],'b_', markersize=8, label="Negative class")
# plt.plot(XP[:,0],XP[:,1],'r+', markersize=8, label="Positive class")
plt.title("Perceptron Algorithm iteration: {}".format(epoch))
# plot decision boundary orthogonal to w
# w is w2,w1, w0 last term is bias.
if len(w) == 3:
a = -w[0] / w[1]
b = -w[0] / w[2]
xx = [ 0, a]
yy = [b, 0]
plt.plot(xx,yy,'--g',label='Decision Boundary')
if len(w) == 2:
x2=[ w[0], w[1], -w[1], w[0]]
x3=[ w[0], w[1], w[1], -w[0]]
x2x3 =np.array([x2,x3])
XX,YY,U,V = list(zip(*x2x3))
ax = plt.gca()
ax.quiver(XX,YY,U,V,scale=1, color='g')
# Add labels
plt.xlabel('X')
plt.ylabel('Y')
# limits
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
# lines from origin
plt.axhline(y=0, color='k', linestyle='--',alpha=0.2)
plt.axvline(x=0, color='k', linestyle='--',alpha=0.2)
plt.grid(True)
plt.legend(loc=1)
plt.show()
# Always clost the plot
plt.close()
def predict(X,w):
return np.sign(np.dot(X, w))
def plot_contour(X,Y,w,mesh_stepsize):
try:
plt.style.use('seaborn-darkgrid')
# plt.style.use('ggplot')
#plt.style.available
except:
pass
# Get data for two classes
idxN = np.where(np.array(Y)==-1)
idxP = np.where(np.array(Y)==1)
XN = X[idxN]
XP = X[idxP]
# plot two classes with + and - sign
fig, ax = plt.subplots()
ax.set_title('Perceptron Algorithm')
plt.xlabel("X")
plt.ylabel("Y")
plt.plot(XN[:,0],XN[:,1],'b_', markersize=8, label="Negative class")
plt.plot(XP[:,0],XP[:,1],'y+', markersize=8, label="Positive class")
plt.legend()
# create a mesh for contour plot
# We first make a meshgrid (rectangle full of pts) from xmin to xmax and ymin to ymax.
# We then predict the label for each grid point and color it.
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# Get 2D array for grid axes xx and yy (shape = 700, 1000)
# xx has 700 rows.
# xx[0] has 1000 values.
xx, yy = np.meshgrid(np.arange(x_min, x_max, mesh_stepsize),
np.arange(y_min, y_max, mesh_stepsize))
# Get 1d array for x and y axes
xxr = xx.ravel() # shape (700000,)
yyr = yy.ravel() # shape (700000,)
# ones vector
# ones = np.ones(xxr.shape[0]) # shape (700000,)
ones = np.ones(len(xxr)) # shape (700000,)
# Predict the score
Xvals = np.c_[ones, xxr, yyr]
scores = predict(Xvals, w)
# Plot contour plot
scores = scores.reshape(xx.shape)
ax.contourf(xx, yy, scores, cmap=plt.cm.Paired)
# print("xx.shape = {}".format(xx.shape)) # (700, 1000)
# print("scores.shape = {}".format(scores.shape)) # (700, 1000)
# print("scores[0].shape = {}".format(scores[0].shape)) # (1000,)
# show the plot
plt.savefig("Perceptron.png")
plt.show()
plt.close()
def perceptron_sgd(X, Y,epochs):
"""
X: data matrix without bias.
Y: target
"""
# add bias to X's first column
ones = np.ones(X.shape[0]).reshape(X.shape[0],1)
X1 = np.append(ones, X, axis=1)
w = np.zeros(X1.shape[1])
final_iter = epochs
for epoch in range(epochs):
print("\n")
print("epoch: {} {}".format(epoch, '-'*30))
misclassified = 0
for i, x in enumerate(X1):
y = Y[i]
h = np.dot(x, w)*y
if h <= 0:
w = w + x*y
misclassified += 1
print('misclassified? yes w: {} '.format(w,i))
else:
print('misclassified? no w: {}'.format(w))
pass
if misclassified == 0:
final_iter = epoch
break
return w, final_iter
def gen_lin_separable_data(data, data_tr, data_ts,data_size):
mean1 = np.array([0, 2])
mean2 = np.array([2, 0])
cov = np.array([[0.8, 0.6], [0.6, 0.8]])
X1 = np.random.multivariate_normal(mean1, cov, size=int(data_size/2))
y1 = np.ones(len(X1))
X2 = np.random.multivariate_normal(mean2, cov, size=int(data_size/2))
y2 = np.ones(len(X2)) * -1
with open(data,'w') as fo, \
open(data_tr,'w') as fo1, \
open(data_ts,'w') as fo2:
for i in range( len(X1)):
line = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X1[i][0], X1[i][1], y1[i])
line2 = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X2[i][0], X2[i][1], y2[i])
fo.write(line)
fo.write(line2)
for i in range( len(X1) - 20):
line = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X1[i][0], X1[i][1], y1[i])
line2 = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X2[i][0], X2[i][1], y2[i])
fo1.write(line)
fo1.write(line2)
for i in range((len(X1) - 20), len(X1) ):
line = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X1[i][0], X1[i][1], y1[i])
line2 = '{:5.2f} {:5.2f} {:5.0f} \n'.format(X2[i][0], X2[i][1], y2[i])
fo2.write(line)
fo2.write(line2)
def main():
"""Run main function."""
# generate linearly separable data
data = 'data.txt'
data_tr = 'data_train.txt'
data_ts = 'data_test.txt'
data_size = 200
gen_lin_separable_data(data, data_tr, data_ts,data_size)
# read data
epochs = 20
X_train, Y_train = read_data(data_tr)
X_test, Y_test = read_data(data_ts)
# fit perceptron
w, final_iter = perceptron_sgd(X_train,Y_train,epochs)
print('w = ', w)
plot_boundary(X_test,Y_test,w,final_iter)
# contour plot
mesh_stepsize = 0.01
plot_contour(X_test,Y_test,w,mesh_stepsize)
if __name__ == "__main__":
main()
决策边界如下所示:
关于python - 如何在 Python 中实现感知机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47213847/
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我刚刚开始使用 Arduino,对更多高级内容几乎一无所知。这看起来很简单。现在我是一个通常喜欢将两个设备集成在一起的人,所以我想知道我是否可以使用计算机的键盘或连接到 Arduino 板上的两个硬件
Hadoop上是否有支持 vector 机的实现? 我正在寻找使我能够训练然后在Hadoop之上测试SVM模型的代码。 最佳答案 有人正在使用BSP在Apache Hama之上进行实现,该实现基本上是
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我想用 Java 编写一个“智能监视器”,它会在它检测到即将出现的性能问题时发出警报。我的 Java 应用正在将结构化格式的数据写入日志文件: | | 因此,例如,如果我有一个执行时间为 812
我在 Cappuccino 中遇到这种错误 TypeError: Result of expression '_2b' [undefined] is not an object. TypeError:
我想编写一个简单的 bean 机程序。该程序将接受用户输入的球数和槽数,并计算每个球的路径。每个槽中的球数也将打印为直方图。 我尽力让代码保持简短和简洁,但我能做到的最好的长度是 112 行。当我运行
我正在开发一个 Plone 模板。目前我正在对模板实现搜索。模板上有一个表单提交到同一模板,即同一页面。 我需要启用页面的某些部分,即结果 DIV,仅当页面中的表单已提交时。我不确定如何检查页面是否已
我是机器学习的新手。我正在使用 opencv 开源库做一个项目。我的问题是我没有机器学习方面的经验。我从不同的图像中提取了特征并对其进行了评估,现在我想使用 SVM 对这些图像中的对象进行分类,但我不
我有一个来自自定义抽象对象的数据集和一个自定义距离函数。是否有任何好的 SVM 库允许我训练我的自定义对象(不是 2d 点)和我的自定义距离函数? 我在 this similar stackoverf
我正在尝试编写 SVM 或 KNN 程序来对文本文档进行分类。我掌握了两者的概念,但我希望看到一些很好的代码示例,它们专门演示了如何将文本/单词表示为 vector 。有人知道好的教程/文章/讲座/任
我想知道支持 vector 机 (SVM) 对于大型/超大型数据集(5-15M+ 行)具有非线性决策边界(例如高斯核)? 我知道两种特殊的方法:一方面,这个使用随机梯度下降等的调查: http://c
我试图在 Raspberry Pi 中使用 python 控制连续伺服(DF15RSMG),但连续伺服无法停止。代码如下: import RPi.GPIO as GPIO import time
我们在 .net 中有银行项目。在那个项目中我们需要实现存折打印。 - 存折背面会有磁条。 - 当客户将存折插入自助服务终端时,自助服务终端将生成 ISO 8583 信息。 - 为响应此消息,CBS(
我想使用 svm 分类器进行面部表情检测。我知道 opencv 有一个 svm api,但我不知道训练分类器的输入应该是什么。到现在看了很多论文,都是说人脸特征检测后训练分类器。 到目前为止我做了什么
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
为了学习 ArchLinux,我在 VirtualBox 机器上安装并使用了 ArchLinux。它运行完美。现在我在我的电脑上安装了 Docker(Windows 环境)。在安装 Docker 的过
我找不到很多相关信息,但是我知道可以通过命令提示符electron-packager .创建一个 Electron 应用。但是,可以通过 Node 快速路由在前端执行它吗? 所以我想做这样的事情: r
我正在使用 MS Visual Studio 2008、OpenCV、C++ 和 SVM 继续我的 OCR 项目。我生成了一个超过 2000 个机印字符样本的数据集。当我用线性核测试时,我总是得到 9
我通过UART接口(interface)(RX-TX,GND-GND)将伺服(TowerPro sg90)连接到32伺服 Controller (this one)。 卖家提供了如何连接和控制我的伺服
我是一名优秀的程序员,十分优秀!