I was working on a python program. I have created a class named "Perception". The code is given below:
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)
when i want to declare the class in the following line:
ppn = Perceptron(eta=0.1, n_iter=10)
I get the following error:
NameError: name 'Perceptron' is not defined
I am new to Python. Please help me in the next steps. And Thanks in advance.
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)
您应该调用ppn = Perceptron.Perceptron(eta = 0.1,n_iter = 10)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.