Created
April 10, 2019 10:13
-
-
Save nithyadurai87/e6794ec008a7855681db4ba9164b54af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def predict(row, weights): | |
activation = weights[0] | |
for i in range(len(row)-1): | |
activation += weights[i + 1] * row[i] | |
return 1.0 if activation > 0.0 else 0.0 | |
def train_weights(dataset, l_rate, n_epoch): | |
weights = [0.0 for i in range(len(dataset[0]))] | |
for epoch in range(n_epoch): | |
sum_error = 0.0 | |
for row in dataset: | |
error = row[-1] - predict(row, weights) | |
sum_error += error**2 | |
weights[0] = weights[0] + l_rate * error | |
for i in range(len(row)-1): | |
weights[i + 1] = weights[i + 1] + l_rate * error * row[i] | |
print('epoch=%d, error=%.2f' % (epoch, sum_error)) | |
print (weights) | |
dataset = [[0.4,0.3,1], | |
[0.6,0.8,1], | |
[0.7,0.5,1], | |
[0.9,0.2,0]] | |
l_rate = 0.1 | |
n_epoch = 6 | |
train_weights(dataset, l_rate, n_epoch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To improve the efficiency of your code, I made several changes:
optimizing array operations, minimizing redundant computations
and reducing the number of times I convert between list and array.
import numpy as np # pip3 install numpy
def predict(row, weights):
activation = np.dot(weights, row)
return 1.0 if activation > 0.0 else 0.0
def train_weights(dataset, l_rate, n_epoch):
dataset = np.array(dataset) # Convert the entire dataset to a NumPy array once
weights = np.zeros(dataset.shape[1]) # Initialize weights as a NumPy array
dataset = [
[0.4, 0.3, 1],
[0.6, 0.8, 1],
[0.7, 0.5, 1],
[0.9, 0.2, 0]
]
l_rate = 0.1
n_epoch = 6
train_weights(dataset, l_rate, n_epoch)