1+ """
2+ Perceptron Algorithm Implementation
3+ """
4+ import numpy as np
5+
6+
7+ class Perceptron :
8+ """
9+ Perceptron Classifier
10+
11+ Parameters:
12+ -----------
13+ learning_rate : float
14+ Learning rate (between 0.0 and 1.0)
15+ epochs : int
16+ Passes over the training dataset.
17+
18+ Attributes:
19+ -----------
20+ weights : numpy.ndarray
21+ Weights after fitting.
22+ bias : float
23+ Bias unit after fitting.
24+ errors : list
25+ Number of misclassifications (updates) in each epoch.
26+
27+ Examples:
28+ ---------
29+ >>> import numpy as np
30+ >>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
31+ >>> y = np.array([0, 0, 0, 1])
32+ >>> perceptron = Perceptron(learning_rate=0.1, epochs=10)
33+ >>> _ = perceptron.fit(X, y)
34+ >>> perceptron.predict(X).tolist()
35+ [0, 0, 0, 1]
36+ """
37+
38+ def __init__ (self , learning_rate : float = 0.01 , epochs : int = 1000 ) -> None :
39+ self .learning_rate = learning_rate
40+ self .epochs = epochs
41+ self .weights = np .zeros (1 )
42+ self .bias = 0.0
43+ self .errors = []
44+
45+ def fit (self , X : np .ndarray , y : np .ndarray ) -> "Perceptron" :
46+ """
47+ Fit training data.
48+
49+ Parameters:
50+ -----------
51+ X : shape = [n_samples, n_features]
52+ Training vectors, where n_samples is the number of samples
53+ and n_features is the number of features.
54+ y : shape = [n_samples]
55+ Target values.
56+
57+ Returns:
58+ --------
59+ self : object
60+
61+ Examples:
62+ ---------
63+ >>> import numpy as np
64+ >>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
65+ >>> y = np.array([0, 0, 0, 1])
66+ >>> perceptron = Perceptron(learning_rate=0.1, epochs=10)
67+ >>> _ = perceptron.fit(X, y)
68+ """
69+ n_samples , n_features = X .shape
70+ self .weights = np .zeros (n_features )
71+ self .bias = 0.0
72+ self .errors = []
73+
74+ for _ in range (self .epochs ):
75+ errors = 0
76+ for xi , target in zip (X , y ):
77+ # Calculate update
78+ update = self .learning_rate * (target - self .predict (xi ))
79+ self .weights += update * xi
80+ self .bias += update
81+ errors += int (update != 0.0 )
82+ self .errors .append (errors )
83+ return self
84+
85+ def predict (self , X : np .ndarray ) -> np .ndarray :
86+ """
87+ Return class label after unit step
88+
89+ Examples:
90+ ---------
91+ >>> import numpy as np
92+ >>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
93+ >>> y = np.array([0, 0, 0, 1])
94+ >>> perceptron = Perceptron(learning_rate=0.1, epochs=10)
95+ >>> _ = perceptron.fit(X, y)
96+ >>> perceptron.predict(X).tolist()
97+ [0, 0, 0, 1]
98+ """
99+ linear_output = np .dot (X , self .weights ) + self .bias
100+ return self .activation_function (linear_output )
101+
102+ def activation_function (self , x : np .ndarray ) -> np .ndarray :
103+ """
104+ Step activation function: returns 1 if x >= 0, else 0
105+
106+ Examples:
107+ ---------
108+ >>> import numpy as np
109+ >>> perceptron = Perceptron()
110+ >>> perceptron.activation_function(np.array([0.5, -0.5, 0])).tolist()
111+ [1, 0, 1]
112+ """
113+ return np .where (x >= 0 , 1 , 0 )
114+
115+
116+ if __name__ == "__main__" :
117+ import doctest
118+
119+ doctest .testmod ()
120+
121+ # Example usage
122+ X = np .array ([[0 , 0 ], [0 , 1 ], [1 , 0 ], [1 , 1 ]])
123+ y = np .array ([0 , 0 , 0 , 1 ]) # AND gate
124+
125+ perceptron = Perceptron (learning_rate = 0.1 , epochs = 10 )
126+ perceptron .fit (X , y )
127+
128+ print ("Weights:" , perceptron .weights )
129+ print ("Bias:" , perceptron .bias )
130+ print ("Predictions:" , perceptron .predict (X ))
0 commit comments