您的位置:首页 > 编程语言 > Python开发

Implementing a perceptron learning algorithm in Python

2017-04-08 14:05 323 查看
class Perceptron(object):

def __init__(self, eta=0.01, n_iter=10):
self.eta = eta
self.n_iter = n_iter

def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self

def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]

def predict(self, X):
"""Return class label after unit step"""
return np.where(self.net_input(X) >= 0.0, 1, -1)
Usage Example:
Training a perceptron model on the Iris dataset. ( https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data )
df = pd.read_csv("./datasets/iris/iris.data", header=None)
y = df.iloc[0:100, 4].valuesy = np.where(y == 'Iris-setosa', -1, 1)X = df.iloc[0:100, [0, 2]].values
print('Training the perceptron model')
ppn = Perceptron(eta=0.1, n_iter=10)ppn.fit(X, y)
Tips---function:
1. numpy dot  :矩阵乘法
2. numpy where: 三元表达式 x if condition else y 的矢量化
Reference : 《Python Machine Learning》

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python class