-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode in python
More file actions
63 lines (59 loc) · 1.61 KB
/
Copy pathcode in python
File metadata and controls
63 lines (59 loc) · 1.61 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
from random import randrange
from csv import reader
from math import sqrt
def train_test_split(dataset, split):
train = list()
copy = dataset
while len(train) < split * len(dataset):
index = (len(copy))-1
train.append(copy.pop(index))
return train,copy
def rmse_metric(actual, predicted):
sum_error = 0.0
for i in range(len(actual)):
error = predicted[i] - actual[i]
sum_error += (error ** 2)
mean_error = sum_error/len(actual)
return sqrt(mean_error)
def evaluate_algorithm(dataset, split):
train, test = train_test_split(dataset, split)
test_set = list()
for row in test:
test_set.append(list(row))
predictions = list()
b0, b1 = coefficients(train)
for row in test:
yhat = b0 + b1 * row[0]
predictions.append(yhat)
actual = [row[1] for row in test]
r = rmse_metric(actual, predictions)
return r
def mean(values):
return sum(values) / float(len(values))
def covariance(x, mean_x, y, mean_y):
covar = 0.0
for i in range(len(x)):
covar += (x[i] - mean_x) * (y[i] - mean_y)
return covar
def variance(values, mean):
return sum([(x-mean)**2 for x in values])
def coefficients(dataset):
x = [row[0] for row in dataset]
y = [row[1] for row in dataset]
x_mean, y_mean = mean(x), mean(y)
b1 = covariance(x, x_mean, y, y_mean) / variance(x, x_mean)
b0 = y_mean - b1 * x_mean
return [b0, b1]
dataset = list()
with open('sabya.csv', 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
for i in range(len(dataset[0])):
for row in dataset:
row[i] = float(row[i])
split = 0.6
rmse = evaluate_algorithm(dataset, split)
print('RMSE: %.3f' % (rmse))