Skip to content

Commit 64f673a

Browse files
committed
perceptron training
1 parent 3750a15 commit 64f673a

File tree

7 files changed

+553
-386
lines changed

7 files changed

+553
-386
lines changed
17.7 KB
Loading

content/Excalidraw/Drawing 2025-08-27 18.48.54.excalidraw.md

Lines changed: 296 additions & 384 deletions
Large diffs are not rendered by default.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
```python
2+
3+
class Vector:
4+
def __init__(self,vlist):
5+
self.vlist=vlist.copy()
6+
self.n_dim=len(vlist)
7+
8+
9+
def __repr__(self):
10+
return str(self.vlist)
11+
12+
def len(self):
13+
return len(self.vlist)
14+
15+
def __getitem__(self,index):
16+
return self.vlist[index]
17+
18+
def __setitem__(self, index, val):
19+
self.vlist[index] = val
20+
21+
def copy(self):
22+
new=Vector(self.vlist)
23+
return new
24+
25+
def check_dim(self,v2):
26+
if type(v2) != Vector:
27+
raise Exception("vector expected")
28+
if self.n_dim != v2.n_dim:
29+
raise Exception("v not same size")
30+
31+
def __eq__(self, v2):
32+
self.check_dim(v2)
33+
34+
for i in range(self.len()):
35+
if self[i]!=v2[i]:
36+
return False
37+
return True
38+
39+
def __add__(self,v2):
40+
self.check_dim(v2)
41+
new=[None for _ in range(self.len())]
42+
for i in range(self.len()):
43+
new[i]=self[i]+v2[i]
44+
45+
vnew=Vector(new)
46+
return vnew
47+
48+
def __sub__(self,v2):
49+
self.check_dim(v2)
50+
new=[None for _ in range(self.len())]
51+
for i in range(self.len()):
52+
new[i]=self[i]-v2[i]
53+
vnew=Vector(new)
54+
return vnew
55+
56+
def __mul__(self,v2):
57+
if type(v2)==Vector:
58+
return self.dotP(v2)
59+
else:
60+
return self.scalar_mul(v2)
61+
62+
def __div__(self,v2):
63+
if type(v2)==Vector:
64+
raise Exception("scalar div only")
65+
return self.scalar_div(v2)
66+
67+
def scalar_mul(self,v2:float):
68+
new=[None for _ in range(self.len())]
69+
for i in range(self.len()):
70+
new[i]=self[i]*v2
71+
72+
vnew=Vector(new)
73+
return vnew
74+
75+
def scalar_div(self,v2:float):
76+
new=[None for _ in range(self.len())]
77+
for i in range(self.len()):
78+
new[i]=self[i]/v2
79+
80+
vnew=Vector(new)
81+
return vnew
82+
83+
84+
def dotP(self,v2):
85+
"""DOT PRODUCT"""
86+
self.check_dim(v2)
87+
new=[None for _ in range(self.len())]
88+
for i in range(self.len()):
89+
new[i]=self[i]*v2[i]
90+
return sum(new)
91+
92+
def norm(self)->float:
93+
sqsum=0
94+
for v in self.vlist:
95+
sqsum+=v**2
96+
return sqsum**(0.5)
97+
```

content/Unit 4/Artificial Intelligence/Machine Learning/Classification/Classification types/Linear classification/Margin boundaries (Linear).md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Using [[Vector notation for weight and data]]
1616

1717
Let $h(x)=x\cdot w+b$ ($b$=bias)
1818
If $h(x)=0$ represents the decision boundary, then $h(x)=k,k\neq{0}$ represents margin boundaries.
19+
Note that $\dots+b$ and $\dots-b$ in the formula is often interchangeable, as b can be negative or positive, and is adjusted during training anyways, just need to ensure its consistant.
1920

2021
More specifically
2122
- **Class +1 boundary**
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
A program/algorithm (in this case artificial intelligence) with the goal of divides data points into predefined groups called classes.
22

3+
Often make use of [[Perceptron|Perceptron/s]]
4+
35
Take the IRIS data set as an example, which contains measurements of many flowers.
46
Classification in this data set could involve classifying flowers into their types based on the measurements from the dataset.

content/Unit 4/Artificial Intelligence/Machine Learning/Vector notation for weight and data.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,6 @@ You may recognise this from Specialist Maths as the cartesian equation for a pla
4242
Here $r$, or the position vector, is represented by $x$.
4343
This makes $w$ the normal vector.
4444
**$w$ will always be normal to classification (decision and margin) boundaries**.
45-
%% NOT SUREL Note that the magnitude of $w$ is not significant as the bias and $w$ are both adjusted during training. %%
46-
![[Pasted image 20250828221537.png]]
45+
$w$ affects the margin.
46+
47+
![[Pasted image 20250829121703.png]]

content/Unit 4/Artificial Intelligence/Neural Networks/Perceptron.md

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,160 @@ Linear seperation
5454
- requires labelled data for training
5555
[[Multi-layer Perceptron]] overcomes these limitations.
5656

57+
58+
59+
# Code
60+
61+
62+
## Example of a perceptron
63+
```python
64+
def perceptron(feature_l,weight_l,bias):
65+
product_list=[feature_l[i]*weight_l[i] for i in range(len(feature_l))]
66+
result=sum(product_list)+bias
67+
if result>0:
68+
return 1
69+
else:
70+
return 0
71+
```
72+
73+
74+
## Example of perceptron training
75+
76+
**NOTE:** This uses a vector module, which can be copied here: [[Vectors]]
77+
78+
```python
79+
from ucimlrepo import fetch_ucirepo
80+
from dataclasses import dataclass
81+
import random
82+
from tqdm import tqdm
83+
84+
#This uses a personal vector module, which can be copied from
85+
# algo25/python/Personal Modules/Vectors
86+
# Use the folling import line, or just copy paste the entire vector class here
87+
from Vector import Vector
88+
89+
90+
@dataclass
91+
class AIconfig:
92+
data_points: list[Vector]=None
93+
targets:list=None
94+
weights:Vector=None
95+
bias:float=None
96+
97+
98+
def get_data():
99+
# fetch dataset
100+
iris = fetch_ucirepo(id=53)
101+
102+
# data (as pandas dataframes)
103+
iris_features = iris.data.features
104+
iris_targets = iris.data.targets
105+
106+
# get features as seperate lists
107+
SL=iris_features["sepal length"]
108+
SW=iris_features["sepal width"]
109+
PL=iris_features["petal length"]
110+
PW=iris_features["petal width"]
111+
112+
qty=len(SL)
113+
114+
# obtain features by combining data points
115+
X1=[SL[i]*SW[i] for i in range(qty)]
116+
X2=[PL[i]*PW[i] for i in range(qty)]
117+
118+
# obtain lists of targets, or correct answers
119+
Y=[(1 if fclass == "Iris-setosa" else 0) for fclass in iris_targets["class"]]
120+
121+
# we will store all data points as vectors
122+
vectorlist=[]
123+
for i in range(len(X1)):
124+
vl=[X1[i],X2[i]]
125+
vectorlist.append(Vector(vl))
126+
127+
return vectorlist,Y
128+
129+
130+
131+
def perceptron(x:Vector,w:Vector,b):
132+
# simple perceptron
133+
# DOT PRODUCT OF x and w vectors + bias
134+
result=x*w+b
135+
if result>0:
136+
return 1
137+
else:
138+
return 0
139+
140+
141+
def normal_train(config:AIconfig,nEpoch=1000,learnRate=0.01):
142+
# training
143+
144+
# gets list of data vectors (x)
145+
x_l=config.data_points
146+
147+
# finds number of entries,
148+
n_entries=len(x_l)
149+
# finds number of features
150+
n_features=x_l[0].len()
151+
152+
# populates a weight vector with samed dimensions as data vector
153+
wl=[0 for _ in range(n_features)]
154+
config.weights=Vector(wl)
155+
del wl
156+
157+
targets=config.targets
158+
159+
# initiate a bias
160+
config.bias=0
161+
162+
for _ in tqdm(range(nEpoch)): #
163+
164+
# iterate through all data items in random order
165+
i_list=list(range(n_entries))
166+
random.shuffle(i_list)
167+
for i in i_list:
168+
x=x_l[i]
169+
w=config.weights
170+
bias=config.bias
171+
172+
res=perceptron(x,w,bias)
173+
174+
# calculates error (if correct, error = 0)
175+
error=targets[i]-res
176+
177+
# modifies bias and weights
178+
bias+= error * learnRate
179+
config.weights+=(x*error)*learnRate
180+
return config
181+
182+
183+
def main():
184+
# extract data
185+
x_l,targets=get_data()
186+
187+
# initiate config
188+
config=AIconfig()
189+
config.data_points=x_l
190+
config.targets=targets
191+
192+
# initiates training
193+
normal_train(config)
194+
195+
# outputs the final configuration
196+
print(f"weights {config.weights}")
197+
print(f"bias {config.bias}")
198+
199+
main()
200+
201+
```
202+
203+
204+
205+
206+
207+
208+
209+
210+
57211
[^1]: https://www.geeksforgeeks.org/machine-learning/what-is-perceptron-the-simplest-artificial-neural-network/
58212

59213
[^2]: https://www.w3schools.com/ai/ai_perceptrons.asp

0 commit comments

Comments
 (0)