感知机实现代码,运行后出现错误,搞不明白了,有没有大佬帮忙看下
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
import Perceptron2 as perceptron_class
from sklearn.linear_model import Perceptron
from itertools import *
import Perceptron
class Percetron(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]) # X的列数+1
self.errors_ = []
for _ in range(self.n_iter): # 迭代次数
errors = 0
for xi, target in zip(X, y): # 将X,y组成
update = self.eta * (target - self.predict(xi)) # 预测目标和实际目标是否相同
self.w_[1:] += update * xi # 更新
self.w_[0] += update # 更新b
errors += int(update != 0.0) # 记录这次迭代的错误数
self.errors_.append(errors)
return self
def net_input(self, X): # 输入X,输出结果
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1) # 如果结果大于等于0,返回1,否则返回0
def plot_decision_regions(X, y, classifier, resolution=0.02): # 绘制决策边界
markers = ('s', 'x', 'o', '^', 'v') # 标记
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') # 颜色
cmap = ListedColormap(colors[:len(np.unique(y))]) # 定义一些颜色和标记符号,并通过颜色列表生成了颜色示例图
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 # 对最大值和最小值做出限定
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
z = Z.reshape(xx1.shape)
plt.xlim(xx1.min(), xx1.max()) # x轴范围
plt.ylim(xx2.min(), xx2.max()) # y轴范围
for idx, c1 in enumerate(np.unique(y)):
plt.scatter(x=X[y == c1, 0], y=X[y == c1, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=c1)
if name == "__main__":
df = pd.read_csv("vgsales.csv", header=None, encoding='gbk')
df.tail() # 用于显示数据的最后五行以确保加载成功
y = df.iloc[0:100, 4].values # 此时y是类别名称
y = np.where(y == 'Iris-setosa', -1, 1) # 若是这个名称则为-1,不是则为1
X = df.iloc[0:100, [3, 10]].values # 从表中获得X
# plt.scatter(X[:50,0],X[:50,1],color='red',marker='o',label='Year')
# plt.scatter(X[50:100,0],X[50:100,1],color='blue',marker='x',label='Global_Sales')
# plt.xlabel('petal length')
# plt.ylabel('sepal length')
# plt.legend(loc='upper left')
# plt.show()
ppn = Perceptron.Percetron(eta=0.01, n_iter=10) # 初始化感知器
ppn.fit(X, y) # 拟合感知器
plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') # 横坐标从1到len(errors_),纵坐标为errors_,
plt.xlabel('Epochs')
plt.ylabel('Number of misclassifications')
plt.show()
plot_decision_regions(X, y, classifier=ppn)
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')
plt.show()
Traceback (most recent call last):
File "E:/python-program/exercise.py", line 66, in
ppn.fit(X, y) # 拟合感知器
File "E:\python-program\Perceptron.py", line 15, in fit
update=self.eta*(target-self.predict(xi))#预测目标和实际目标是否相同
File "E:\python-program\Perceptron.py", line 24, in predict
return np.where(self.net_input(X)>=0.0,1,-1)#如果结果大于等于0,返回1,否则返回0
File "E:\python-program\Perceptron.py", line 22, in net_input
return np.dot(X,self.w_[1:])+self.w_[0]
File "<__array_function__ internals>", line 5, in dot
TypeError: can't multiply sequence by non-int of type 'float'