Perceptron model implementation

1, python programming from:

Import numpy AS NP
 Import matplotlib.pyplot AS PLT 

class MyPerceptron:
     DEF  the __init__ (Self): 
        self.w = Number of the Number None # parameters w and x corresponds to the initial features x does not know the number, so the assignment None 
        self.b, = 0 
        self.l_rate = # learning rate. 1. 1 = DEF Fit (Self, X_train, y_train):
         # number of samples characterized by updating the initial point w, as x1 = (3,3) T, wherein there are two , = the self.w [0,0] 
        self.w = np.zeros (X_train.shape [. 1 ]) 
        I = 0
         the while I < X_train.shape [0]: 
            X- = X_train [I] 
            Y =

    y_train [I]
             # If y * (wx + b) ≤0 misjudgment point instructions are updated W, B 
            IF Y * (np.dot (self.w, X-) + self.b,) <= 0: 
                Self. W = self.w * + self.l_rate np.dot (Y, X-) 
                self.b, = + self.l_rate * self.b, Y 
                I = 0 # If misjudgment point, the head detects 
            the else : 
                I + =. 1 DEF Draw (X-, W, B):
     # points on the separating hyperplane production 
    X_new np.array = ([[0], [. 6 ]]) 
    y_predict =-b- (W [0] * X_new) / W [1 ]
     # plotted scattergram training data set 
    plt.plot (X-[: 2,0], X-[: 2,1], " G *

" , Label = " . 1 " ) 
    plt.plot (X-[ 2:, 0], X-[2:, 0], " RX " , label = " -1 " )
     # draw separating hyperplane 
    plt.plot (X_new, y_predict, " B- " )
     # set the start and end values of two coordinate axes 
    plt.axis ([0,6,0,6 ])
     # set axis labels 
    plt.xlabel ( ' X1 ' ) 
    plt.ylabel ( ' X2 ' )
     # show Legend 
    plt.legend ()
     # display images 
    plt.show () 

DEFmain ():
     # configured training data set 
    X_train np.array = ([[3,3], [4,3-], [1,1 ]]) 
    y_train = np.array ([1,1, -1 ])
     # Construction perceptron object to continue training dataset 
    Perceptron = MyPerceptron () 
    perceptron.fit (X_train, y_train) 
    Print (perceptron.w)
     Print (perceptron.b)
     # result image drawing 
    draw (X_train, perceptron.w, perceptron. b) 

IF  __name__ == " __main__ " : 
    main ()

 2, call sklearn achieve:

from sklearn.linear_model import Perceptron
import numpy as np

X_train = np.array([[3, 3], [4, 3], [1, 1]])
y = np.array([1, 1, -1])

perceptron=Perceptron()
perceptron.fit(X_train,y)
print("w:",perceptron.coef_,"\n","b:",perceptron.intercept_,"\n","n_iter:",perceptron.n_iter_)

res=perceptron.score(X_train,y)
print("correct rate:{:.0%}".format(res))

 

Guess you like

Origin www.cnblogs.com/WJZheng/p/11243275.html