# Εκπαιδευμένα βάρη και διαδικασία prediction import random import math import csv import torch import torch.nn as nn class SimpleMLP(nn.Module): def __init__(self): super(SimpleMLP, self).__init__() self.layer1 = nn.Linear(6, 32) self.layer2 = nn.Linear(32, 16) self.output = nn.Linear(16, 1) def sigmoid(x): return 1 / (1 + math.exp(-x)) def relu(x): if x>0 : return x else : return 0.001*x def calculate_hidden1(inputs, hidden1): for j in range(hidden1): a = 0 for i in range(inputs): a = a + inp[i] * i_h1_w[j][i] #i, j a = relu(a + h1_b[j]) h1.append(a) def calculate_hidden2(hidden1, hidden2): for j in range(hidden2): a = 0 for i in range(hidden1): a = a + h1[i] * h1_h2_w[j][i] #i,j a = relu(a + h2_b[j]) h2.append(a) def calculate_output(hidden2): a = 0 for i in range(hidden2): a = a + h2[i] * h2_o_w[i] return sigmoid(a + o_b) # ΚΥΡΙΩΣ ΠΡΟΓΡΑΜΜΑ i_h1_w = [] h1_h2_w = [] h2_o_w = [] h1_b = [] h2_b = [] outp = 0 o_b = 0 model = SimpleMLP() model.load_state_dict(torch.load("road_danger_mlp_weights.pth")) model_dict = model.state_dict() i_h1_w = model_dict['layer1.weight'].tolist() h1_b = model_dict['layer1.bias'].tolist() h1_h2_w = model_dict['layer2.weight'].tolist() h2_b = model_dict['layer2.bias'].tolist() h2_o_w = model_dict['output.weight'].tolist()[0] o_b = float(model_dict['output.bias'].tolist()[0]) mse = 0 count = 0 # Open file with open("datafile2.csv") as file_obj: # Skips the heading heading = next(file_obj) # Create reader object reader_obj = csv.reader(file_obj) # Iterate over each row in the csv file for row in reader_obj: #print(row) inp = [] for i in range(7): if i<6: inp.append(float(row[i])) else: target = float(row[i]) #print(inp) h1 = [] calculate_hidden1(6, 32) h2 = [] calculate_hidden2(32, 16) outp = calculate_output(16) error = target - outp print("output: ", outp, " target: ", target, " error: ", error) mse = mse + error**2 count = count + 1 mse = mse / count print("MSE: ", mse)