-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerceptronAlgorithm.py
More file actions
120 lines (74 loc) · 3.18 KB
/
PerceptronAlgorithm.py
File metadata and controls
120 lines (74 loc) · 3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import numpy as np
import pandas as pd
# This function trains the Perceptron model on the given training data
def Perceptron(trainData, alfa, epochs):
X = trainData.iloc[:, 1:-1].values # Extracting features from columns (ignoring subject id and class)
y = trainData.iloc[:, -1].values # Extracting class labels (the last column)
#print("X HEAD", X)
#print("Y HEAD", y)
weights = np.zeros(X.shape[1]) # Initialize weights to zero for each feature
bias = 0
# Iterate over the training data for a fixed number of epochs (1000)
for _ in range(epochs):
# For each sample in the training data
for i in range(len(X)):
# Calculate the prediction by multiplying the features with weights and adding
prediction = np.dot(X[i], weights) + bias
if prediction < 0:
predictionClass = 2
else:
predictionClass = 4
# w = w + alfa.(gercekDeger - tahmin).x
# bias = bias + alfa.(gercekDeger - tahmin)
# If the predicted class is different from the actual class
if predictionClass != y[i]:
error = y[i] - predictionClass
weights += alfa * error * X[i]
bias += alfa * error
return weights, bias
# This function makes a prediction for each sample based on learned weights and bias
def Predict(X, weights, bias):
predict = np.dot(X, weights) + bias
if predict < 0:
return 2
else:
return 4
# This function tests the model on the test dataset and returns the predictions
def Test(testData, weights, bias):
# Extract features from the test data (excluding subject id and class label)
testX = testData.iloc[:, 1:-1].values
# List to store predictions for each test sample
testPredictions = []
# For each sample in the test set, use the Predict function to make predictions
for i in range(len(testX)):
testPrediction = Predict(testX[i], weights, bias)
testPredictions.append(testPrediction)
return testPredictions
# Fill the empty Class column in TESTData with the Predictions I found
def Save(testData, predictions):
updatedTESTData = testData.copy()
updatedTESTData['Class'] = predictions
save = input("\nDo you want to save the updated data to 'Updated_TESTData.xlsx'? (y/n): ").strip().lower()
if save == 'y':
updatedTESTData.to_excel("Updated_TESTData.xlsx", index=False)
print("\nFile saved successfully as 'Updated_TESTData.xlsx'.")
else:
print("\nFile was not saved.\n")
def main():
file = "DataForPerceptron.xlsx"
trainData = pd.read_excel(file, sheet_name='TRAINData')
testData = pd.read_excel(file, sheet_name='TESTData')
"""
print("Train Data:")
print(trainData.head())
print("\nTest Data:")
print(testData.head())
"""
weights, bias = Perceptron(trainData, alfa = 0.1, epochs=1000)
#print(f"Weights {weights} ---- Bias {bias}")
predictions = Test(testData, weights, bias)
print("\nPredictions:", predictions)
Save(testData, predictions)
main()
####### Written by #######
###### Zer0-Bug ######