AttributeError: 'Perception' object has no attribute 'w_'
AttributeError: 'Perception' object has no attribute 'w_'
我的代码
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 29 20:32:51 2017
@author: yangqiusong
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def plot_decision_regions(X, Y, classifier, resolution = 0.02):
markers =('s','x','o','v')
colors = ('read', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(Y))])
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
#print x1_min, x2_min
# print x1_max, x2_max
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
#print xx1
#print xx2
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
print xx1.ravel()
print xx2.ravel()
print Z
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, alpha = 0.4, cmap = cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(Y)):
plt.scatter(x=X[Y==cl, 0], y=X[Y==cl, 1], alpha = 0.8, c = cmap(idex),
marker = markers[idx], label = cl)
class Perception(object):
"""
eta:学习率
n_iter:权重向量的训练次数
w_:神经分叉权重向量
errors_: 用于记录神经元判断出错次数
"""
def __init__(self, eta = 0.01, n_iter = 10):
self.eta = eta
self.n_iter = n_iter
#self.w_ = np.zero(1+X.shape[1])
#self.errors_ = []
def fit(self, X, Y):
"""
输入训练数据,培训神经元,X输入样本向量,Y对应样本分类
X:shape[n_samples, n_features]
X:[[1,2,3], [4,5,6]]
n_samples: 2
n_features: 3
y:[1,-1]
初始化权重向量为0
加一是因为前面算法提到的w0,也就是步调函数阈值
"""
self.w_ = np.zeros(1+X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
"""
X:[[1,2,3],[4,5,6]]
Y:[1,-1]
zip(X,Y) = [[1,2,3,1],[4,5,6,-1]]
"""
for xi, target in zip(X, Y):
"""
update = eta*(Y - Y')
"""
update = self.eta*(target - self.predict(xi))
"""
xi 是一个向量
update * xi 等价:
[da_w(1) = X[1]*update,da_w(2) = X[2]*update,da_w(3) = X[3]*update]
"""
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
def net_input(self,X):
"""
z = w0*1 + w1*X1 + ... + wn*Xn
"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0, 1, -1)
file = 'data.txt'
df = pd.read_csv(file, header = None)
Y = df.loc[0:100, 4].values
Y = np.where(Y == 'Iris-setosa', -1, 1)
X = df.iloc[0:100, [0,2]].values
"""
plt.scatter(X[:50, 0], X[:50, 1], color = 'red', marker = 'o', label = 'setosa')
plt.scatter(X[50:100, 0], X[50:100, 1], color = 'blue', marker = 'x', label = 'versicolor')
plt.xlabel('花瓣长度')
plt.ylabel('花经长度')
plt.legend(loc = 'upper left')
#plt.show()
"""
ppn = Perception(eta = 0.1, n_iter = 10)
plot_decision_regions(X, Y, ppn, resolution = 0.02)
plt.xlabel('花瓣长度')
plt.ylabel('花经长度')
plt.legend(loc = 'upper left')
plt.show()