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》
相关文章推荐
- Perceptron Learning Algorithm(python实现)
- [原创] Learning in Python:Chapter 4 Introducing Python Object Types
- scikit-learn: machine learning in Python
- Machine Learning in Python (Scikit-learn)-(转)
- Perceptron Learning Algorithm (PLA)
- Comprehensive learning path – Data Science in Python深度学习路径-用python进行数据学习
- [原创] Learning in Python:Chapter 3 How You Run Programs
- machine learning in coding(python):使用xgboost构建预测模型
- Machine Learning in Python (Scikit-learn)-(No.1)
- 3.2.5 building machine learning system in python page 42
- machine learning in coding(python):根据关键字合并多个表(构建组合feature)
- scikit-learn: machine learning in Python
- Digression:The perceptron learning algorithm(感知机学习算法)
- 感知机学习算法的几何解释(perceptron learning algorithm)
- Machine Learning in Python (Scikit-learn)-(No.2)
- [原创] Learning in Python:Chapter 5 Numeric Types
- Algorithm in Python(1)
- 【转载】Implementing a Principal Component Analysis (PCA) in Python step by step
- Algorithm: quick sort implemented in python 算法导论 快速排序
- machine learning in coding(python):pandas数据包DataFrame数据结构简介