2017-07-04 52 views
-1

我正在研究python程序。我創建了一個名爲「感知」的類。下面的代碼給出:NameError:python中未定義名稱'classname'

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 :名稱'Perceptron'未定義

我是Python新手。請在下一步中幫助我。並提前致謝。

+1

是否在不同的文件中使用該類(即'ppn = Perceptron(eta = 0.1,n_iter = 10)')? – inspectorG4dget

+1

添加到上面,你可能需要先導入'Perceptron'。 –

回答

1
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)