我正在研究一个python程序。我创建了一个名为" Perception"的类。代码如下:
import numpy as np
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)

当我想在以下行中声明该类时:
ppn = Perceptron(eta=0.1, n_iter=10)
我收到以下错误:
NameError:name' Perceptron'未定义
我是Python新手。请在接下来的步骤中帮助我。并提前致谢。
答案 0 :(得分:2)
Run this it should work , if not share the screen hot of code and output.
import numpy as np
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)
ppn = Perceptron(eta=0.1, n_iter=10)
答案 1 :(得分:0)
您应该调用ppn = Perceptron.Perceptron(eta = 0.1,n_iter = 10)