-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiris.py
56 lines (49 loc) · 1.42 KB
/
iris.py
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
#
# Name: iris.py
# Description: Implementation of an artifical neural network
# for classifying the iris flower types as specified in the
# Iris dataset found at:
#
# http://archive.ics.uci.edu/ml/datasets/Iris
#
# Author(s): Kyle Burnett
#
import random
import math
filename = "iris.data"
basket = []
with open(filename) as ifs:
for line in ifs:
sample = line.strip().split(',')
for i in range(4):
sample[i] = float(sample[i])
basket.append(sample)
# Sigmoid function f(x) = 1 / (1 + e^(-x))
def sigmoid(x):
return 1 / (1 + math.exp(-x))
# Use for propogating signals through the network
def forwardfeed(sample, weights):
total = 0.0
for x, weight in zip(sample, weights):
total += x * weight
return sigmoid(total)
# Initialize weights
w = [0.0, 0.0, 0.0, 0.0]
alpha = 0.1
# This, right now, doesn't enforce not having duplicates, i.e., major
# overfitting problems.
for i in range(100):
# Choose sample
sample = random.choice(basket)
# Feed input data in (feedforward)
sigma = forwardfeed(sample[:-1], w)
# Compute error gradient
if sample[4] == 'Iris-setosa':
# Here the expected value is 1.0
error = sigma * (1.0 - sigma) * (1.0 - sigma)
else:
# Here the expected value is 0.0
error = sigma * (1.0 - sigma) * (0.0 - sigma)
# Update weights
for j in range(4):
w[j] = w[j] + alpha * sample[j] * error