Skip to content

Commit 8b7bf79

Browse files
authored
Merge pull request #21 from joshiayush/dev - Added "Perceptron" API - "single layer neural network"
2 parents c6afcc5 + 31a6de0 commit 8b7bf79

File tree

4 files changed

+74
-6
lines changed

4 files changed

+74
-6
lines changed

CHANGELOG.md

+15
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
# Changelog
22

3+
## ai — 2024-12-28
4+
5+
### Added
6+
7+
- Added examples on "Perceptron" - single layer neural network ([#659fd15](https://www.github.com/joshiayush/ai/commit/659fd15))
8+
- Added implementation of "Perceptron" - single layer neural network ([#c6afcc5](https://www.github.com/joshiayush/ai/commit/c6afcc5))
9+
- Added `statistic` calculating functions to `ai.stats` module (#20) ([#ae05cf1](https://www.github.com/joshiayush/ai/commit/ae05cf1))
10+
11+
## docs — 2024-12-28
12+
13+
### Added
14+
15+
- Added a __Support Vector Machine__ model trained for face recognition ([#912c4c2](https://www.github.com/joshiayush/ai/commit/912c4c2))
16+
17+
318
## ai — 2024-01-04
419

520
### Added

ai/linear_model/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
2222
* `ai.linear_model.linear.LinearRegression`
2323
* `ai.linear_model.logistic.LogisticRegression`
24+
* `ai.linear_model.perceptron.Perceptron`
2425
"""
2526

2627
from .linear import LinearRegression
2728
from .logistic import LogisticRegression
29+
from .perceptron import Perceptron

ai/linear_model/perceptron.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(self,
4848
order to reach to a effecient prediction that minimizes the loss.
4949
random_state: Seed to generate random weights and bias.
5050
"""
51-
self.aplha = alpha
51+
self.alpha = alpha
5252
self.n_iters = n_iters
5353
self.random_state = random_state
5454

@@ -65,16 +65,16 @@ def fit(self, X: np.ndarray, y: np.ndarray) -> 'Perceptron':
6565
"""
6666
rgen = np.random.RandomState(self.random_state)
6767
self.weights = rgen.normal(loc=0.0, scale=0.01, size=X.shape[1])
68-
self.b = np.float(0.)
69-
self.errors = []
68+
self.b_ = np.float64(0.)
69+
self.errors_ = []
7070
for _ in range(self.n_iters):
7171
errors = 0
7272
for xi, target in zip(X, y):
7373
update = self.alpha * (target - self.predict(xi))
7474
self.weights += update * xi
75-
self.b += update
75+
self.b_ += update
7676
errors += int(update != 0.0)
77-
self.errors.append(errors)
77+
self.errors_.append(errors)
7878
return self
7979

8080
def net_input(self, X):
@@ -87,7 +87,7 @@ def net_input(self, X):
8787
Returns:
8888
The dot product of `X` and `weights` plus `b`.
8989
"""
90-
return np.dot(X, self.weights) + self.b
90+
return np.dot(X, self.weights) + self.b_
9191

9292
def predict(self, X):
9393
"""Return class label after unit step.

examples/linear_model/perceptron.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright 2023 The AI Authors. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# pylint: disable=too-many-function-args, invalid-name, missing-module-docstring
15+
# pylint: disable=missing-class-docstring
16+
17+
import matplotlib.pyplot as plt
18+
import numpy as np
19+
import pandas as pd
20+
21+
from ai.linear_model import Perceptron
22+
23+
df = pd.read_csv(
24+
"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data",
25+
header=None,
26+
encoding="utf-8",
27+
)
28+
print(df.tail())
29+
30+
# select setosa and versicolor
31+
y = df.iloc[0:100, 4].values
32+
y = np.where(y == "Iris-setosa", 0, 1)
33+
34+
# extract sepal length and petal length
35+
X = df.iloc[0:100, [0, 2]].values
36+
37+
# plot data
38+
plt.scatter(X[:50, 0], X[:50, 1], color="red", marker="o", label="setosa")
39+
plt.scatter(X[50:100, 0], X[50:100, 1], color="blue", marker="x", label="versicolor")
40+
plt.xlabel("sepal length [cm]")
41+
plt.ylabel("petal length [cm]")
42+
plt.legend(loc="upper left")
43+
plt.show()
44+
45+
ppn = Perceptron(alpha=0.1, n_iters=10)
46+
ppn.fit(X, y)
47+
48+
plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker="o")
49+
plt.xlabel("Epochs")
50+
plt.ylabel("Number of updates")
51+
plt.show()

0 commit comments

Comments
 (0)