-
Notifications
You must be signed in to change notification settings - Fork 0
/
milestone5cleancode.py
191 lines (145 loc) · 6.45 KB
/
milestone5cleancode.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# -*- coding: utf-8 -*-
"""Milestone5CleanCode.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1XL7ZK2ugq54qZICLb47Ke1OgfI34S9TE
"""
from __future__ import print_function
import numpy as np # to use numpy arrays
import tensorflow as tf # to specify and run computation graphs|
import tensorflow_datasets as tfds # to load training data
import keras
import pandas as pd
from keras import backend
from tensorflow.keras import Model, initializers, regularizers, constraints
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, GRU, Reshape, Bidirectional, Dense, Input, Dropout, LeakyReLU, Concatenate, PReLU, Flatten
from keras.callbacks import EarlyStopping, ModelCheckpoint
import matplotlib.pyplot as plt
from math import sqrt
from google.colab import drive
import csv
import scipy.stats
drive.mount('/content/gdrive')
inputs = pd.read_csv("/content/gdrive/My Drive/Colab Notebooks/AllVariables.csv")
keys = []
for it in inputs:
keys.append(it)
distribution = [4, 9, 25, 26] #horrible design
number_of_tests = len(inputs[keys[0]])
input_short_term = []
input_long_term = []
output = []
for i in range(number_of_tests):
instance = []
if pd.isna(inputs[keys[0]][i]):
continue
for j in range(distribution[0], distribution[1]):
instance.append(round(float(inputs[keys[j]][i])/100, 3))
input_short_term.append(instance)
instance = []
for j in range(distribution[1], distribution[2]):
instance.append(round(float(inputs[keys[j]][i])/100, 3))
input_long_term.append(instance)
output.append(float(inputs[keys[distribution[3] - 1]][i])/100)
training_input_short_term = []
training_input_long_term = []
training_output = []
testing_input_short_term = []
testing_input_long_term = []
testing_output = []
for i in range(8):
for j in range(13):
training_input_short_term.append(input_short_term[j])
training_input_long_term.append(input_long_term[j])
training_output.append(output[j])
del input_short_term[:13]
del input_long_term[:13]
del output[:13]
for k in range(1):
testing_input_short_term.append(input_short_term[k])
testing_input_long_term.append(input_long_term[k])
testing_output.append(output[k])
del input_short_term[0]
del input_long_term[0]
del output[0]
lVLabel = ["Capital_Investment_test", "Labor_Force_Participation_test", "Fixed_Broadband_test",
"RandD_test", "Property_Rights_test", "Freedom_From_Corruption_test", "Fiscal_Freedom_test", "Business_Freedom_test",
"Labor_Freedom_test", "Monetary_Freedom_test", "Trade_Freedom_test", "Investment_Freedom_test", "Financial_Freedom_test",
"Economic_Freedom_Overall_test", "Pop_Above_65_test", "Savings_As_GDP_test"]
num_long_term_variable = len(lVLabel)
trainLV = [[] for i in range(num_long_term_variable)]
testLV = [[] for i in range(num_long_term_variable)]
for i in range(len(training_input_long_term)):
for j in range(num_long_term_variable):
trainLV[j].append(training_input_long_term[i][j])
for i in range(num_long_term_variable):
trainLV[i] = np.array(trainLV[i])
for i in range(len(testing_input_long_term)):
for j in range(num_long_term_variable):
testLV[j].append(training_input_long_term[i][j])
for i in range(num_long_term_variable):
testLV[i] = np.array(testLV[i])
training_input_short_term = np.array(training_input_short_term)
training_input_long_term = np.array(training_input_long_term)
training_output = np.array(training_output)
testing_input_short_term = np.array(testing_input_short_term)
testing_input_long_term = np.array(testing_input_long_term)
testing_output = np.array(testing_output)
short_term_input1 = Input(shape=(5,))
short_term_input2 = Input(shape=(5,))
long_term_input1 = Input(shape=(16,))
x1 = Dense(50)(short_term_input1)
x1 = LeakyReLU(0.2)(x1)
x1 = Dropout(0.35)(x1)
x1 = Dense(50)(x1)
x1 = LeakyReLU(0.2)(x1)
x1 = Dropout(0.5)(x1)
x1 = Dense(50)(x1)
x1 = LeakyReLU(0.2)(x1)
con1 = Concatenate(axis=1)([x1, short_term_input2, long_term_input1])
con1 = Dropout(0.35)(con1)
con1 = Dense(71, activation = "relu")(con1)
con1 = Dropout(0.2)(con1)
con1 = Reshape(target_shape = (1, 71))(con1)
con1 = LSTM(100, return_sequences = True)(con1)
con1 = Dropout(0.2)(con1)
con1 = LSTM(100, return_sequences = True)(con1)
con1 = Dropout(0.35)(con1)
con1 = LSTM(200, return_sequences = True)(con1)
con1 = Dropout(0.35)(con1)
con1 = LSTM(100, return_sequences = True)(con1)
con1 = LSTM(1)(con1)
x2 = Dense(1, activation = None)(long_term_input1)
x2 = Reshape(target_shape= (1, 1))(x2)
x2 = LSTM(100, return_sequences = True)(x2)
x2 = LSTM(1)(x2)
con2 = Concatenate(axis=1)([con1, x2])
output = Dense(1, activation = None)(con2)
SingleLongTermmodel = Model(inputs=[short_term_input1, short_term_input2, long_term_input1], outputs=output)
SingleLongTermmodel.summary()
SingleLongTermmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.005), loss='mae')
training_pred1, training_pred2, training_pred3, y_output = training_input_short_term, training_input_short_term, training_input_long_term, training_output
testing_st1,testing_st2, testing_lt1, testing_outp = testing_input_short_term, testing_input_short_term, testing_input_long_term, testing_output
# Model training and testing results
history = SingleLongTermmodel.fit([training_pred1, training_pred2, training_pred3], y_output, epochs = 120, validation_split = 0.2, batch_size = 5, verbose=1)
y2 = SingleLongTermmodel.evaluate(x=[testing_st1, testing_st2, testing_lt1],y=testing_output, batch_size=3, verbose=1)
def print_loss_graph(history):
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train'], loc='upper left')
plt.show()
# Print training error graph
print_loss_graph(history)
# Plot test results based on countries
X = SingleLongTermmodel.predict(x=[testing_input_short_term, testing_input_short_term, testing_input_long_term])
plt.plot(testing_output*100, 'r+')
plt.plot(X*100, 'b+')
plt.legend(['actual', 'predict'])
plt.xticks(np.arange(start = 0, stop = 8), ['Canada', 'Greece', 'Japan', 'Malaysia', 'South Africa', 'Spain', 'UK', 'USA'], rotation = 45)
plt.title("Actual Real GDP Change vs Predicted Real GDP Change by Country")
plt.xlabel("Countries")
plt.ylabel("Percentage in real GDP change")