-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathprogram2_LinearModel.py
3117 lines (2118 loc) · 81.4 KB
/
program2_LinearModel.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# we use PyTorch
import torch
import numpy as np
import matplotlib.pyplot as plt
# use PyTorch and "autograd"
from torch.autograd import Variable
# define function for creating data
def makedata(numdatapoints):
x = np.linspace(-10, 10, numdatapoints)
#coeffs = [0.5, 5]
# here, 5 is the bias, it is 5*x^0=5
# define the coefficients
coeffs = [2, 0.5, 5]
# polynomial, we evaluate a polynomial
y = np.polyval(coeffs, x)
# polyval is used to create a polynomial dataset
# we now add noise, we add additive noise
y += 2 * np.random.rand(numdatapoints)
# rand(.) is for numbers 0 to 1
return x,y
# define the number of data points
numdatapoints = 10
# we now create the data
inputs, labels = makedata(numdatapoints)
# we create a labeled dataset
# we plot the figure with the data
fig = plt.figure(figsize=(10, 20))
ax1 = fig.add_subplot(121)
# 121 means 1 height, 2 wide, and this is the first figure
ax1.set_xlabel("Input")
ax1.set_ylabel("Output")
#ax1.scatter(np.array(inputs), np.array(labels), s=5)
# the "s=5" is the size of the data points
# we create a scatter plot, we plot y against x
ax1.scatter(np.array(inputs), np.array(labels), s=8)
ax1.grid()
ax2 = fig.add_subplot(122)
ax2.set_title("Error vs Epoch")
ax2.grid()
line1, = ax1.plot(inputs, inputs)
# here, we do not care about the second output
# ion(.) is interactive on
# ion(.) is interactive on, we will update the graphs interactively
plt.ion()
plt.show()
def makefeatures(power):
features = np.ones((inputs.shape[0], len(powers)))
# len(powers) = number of columns
for i in range(len(powers)):
features[:,i] = (inputs**powers[i])
print(features.shape)
return features.T
# we define the class LinearModel
class LinearModel(torch.nn.Module):
def __init__(self):
super().__init__()
# we create a linear layer in our model
self.l = torch.nn.Linear(features.shape[0], 1)
# the inputs is features.shape[0]
# the output is 1
def forward(self, x):
out = self.l(x)
return out
# the list of hyperparameters
epochs = 50
# lr is the learning rate
#lr = 0.2
#lr = 0.000003
lr = 0.000003
#powers = [1, 2]
powers = [1, 2, 3]
# we now create the features
features = makefeatures(powers)
# features.T means transpose of features
datain = Variable(torch.Tensor(features.T))
# we use transpose .T
labels = Variable(torch.Tensor(labels.T))
# we use transpose .T
# we now create our model
mymodel = LinearModel()
# we now use the MSE cost function
criterion = torch.nn.MSELoss(size_average=True)
# size_average=True means divide my m, where m is the number of training data
#criterion = torch.nn.MSELoss()
# we use stochastic gradient descent (SGD)
optimiser = torch.optim.SGD(mymodel.parameters(), lr=lr)
#lr=lr defines the learning rate, the step size of SGD
# training
def train():
costs = []
for e in range(epochs):
prediction = mymodel(datain)
# our criteron is the MSE
cost = criterion(prediction, labels)
# we now use append(.), list1.append(.)
costs.append(cost.data)
print("Epoch", e, "Cost", cost.data[0])
# we get our parameters out
params = [mymodel.state_dict()[i][0] for i in mymodel.state_dict()]
# we set our parameters equal to a list that we define
# we use i, and when i = 1 then we get the first elements out of the dictionary
weights = params[0]
bias = params[1]
optimiser.zero_grad()
# we propagate the errors back
cost.backward()
# we propagate the errors back using gradients, derivatives
optimiser.step()
# we now define the line "line1"
# torch.mm is matrix multiplication
line1.set_ydata(torch.mm(weights.view(1,-1), datain.data.t()) + bias)
# we add a bias term to the matrix-vector multiplication (i.e. to the inner product)
fig.canvas.draw()
ax2.plot(costs)
plt.pause(1)
train()
# use: http://interactivepython.org/runestone/static/pythonds/index.html#
# website: http://interactivepython.org/runestone/static/pythonds/index.html#
# we use: http://interactivepython.org/runestone/static/pythonds/BasicDS/toctree.html
# we use lambda expressions in Python
# use: https://docs.python.org/2/reference/expressions.html#lambda
# we use: https://docs.python.org/2/reference/expressions.html
# website: https://docs.python.org/2/reference/expressions.html#lambda
import numpy as np
# we use Python's build-in functions
# use: https://docs.python.org/3/library/functions.html
# we use *args and **kwargs
# https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
# use one-line code
# write as few lines of code as possible
# use comprehensions
a = [i for i in range(2, 100 + 1, 2)]
print(a)
# we use list comprehensions
a = [i for i in range(1, 101) if i % 2 == 0]
print(a)
# create a generator object, use "(.)"
a = (i for i in range(1, 101) if i % 2 == 0)
# the generator object can be used only once
# the generator object can be used one time only
print(list(a))
print('')
# positional arguments => position matters
# we can call function1 using "function1(y=1, x=2)"
# function with positional arguments x, y
def function1(x, y):
return x - y
# positional arguments: the position matters
print(function1(3, 5))
# named arguments, no matter the order
print(function1(y=3, x=5))
# both positional arguments and named arguments
print(function1(4, y=7))
# in functions, position can matter and can not matter
# positional arguments for function
# positional parameters, function inputs, arguments
print('')
print(max(2,6,9,3))
print(sum([2,6,9,3]))
# functions can have default values
# define a function with default values
def func2(x, y=9, z=1):
# the default value is for z
return (x + y) * z
# If we do not give a value for z, then z=1=(default value)
# we can have default values in functions
# default values go to the end of the arguments
# use: (1) default values, (2) *args, (3) **kwargs
# we use default values, one asterisk (i.e. *) and two asterisks (i.e. **)
# we now use *args and **kwargs
# use: https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
# default arguments can be only at the end, even more than one
g = func2(2, 5, 7)
print(g)
print('')
for i in range(5):
print(i, "-", i ** 2)
# use *args at the end
# we use un-named arguments *args
# (1) *args at the end of the arguments in a function
# (2) default values at the end of the arguments in a function
# *args must be in the end of the arguments
def apodosi(*apodoseis):
k = 1
for i in apodoseis:
k *= i
return k
# use: (1) *args, and (2) **kwargs
# "**kwargs" is a dictionary dict
# we use keys and values
# "**kwargs" is a dictionary and has keys and values
# **kwargs must be at the end and hence after *args
def apodosi(*apodoseis, **kwargs):
# we use the "max" key in the dictionary
if "max" in kwargs:
n = kwargs["max"]
else:
n = len(apodoseis)
k = 1
for i in range(n):
k *= apodoseis[i]
return k
# **kwargs must be at the end and hence after *args
def apodosi2(*apodoseis, **kwargs):
# we use the "max" key in the dictionary
if "max" in kwargs:
# we use min(., len(apodoseis))
n = min(kwargs["max"], len(apodoseis))
else:
n = len(apodoseis)
k = 1
for i in range(n):
k *= apodoseis[i]
return k
print('')
print(apodosi(1.11, 1.22, 1.31))
print(apodosi2(1.11, 1.22, 1.31))
print('')
m = [2.3, 1.4, 1.8, 1.5, 2.4]
# we use: "*m" amd "myFunction(*m)"
# when we have a list m, then we use "*m" to get its elements
print(apodosi(*m, max=3))
print(apodosi2(*m, max=3))
# use *list1 to break the list
print(apodosi2(*m, max=13))
# the function does not work if we do not use "*"
# use *args and **kwargs in functions
# website: https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
# use: https://www.geeksforgeeks.org/args-kwargs-python/
# convert to binary
# convert the number n to binary
n = 14
# we use the stack data structure
# define a list that will be used as a stack
stack1 = []
# stack: the last item that enters the stack is the first item out
# the stack data structure is Last In First Out (LIFO)
# the queue data structure is First In First Out (FIFO)
print('')
# every program uses an execution stack
# the execution stack in Python is short
# Every program has a stack that contains the parameters and the local variables of the functions
# that have been called. The stack is LIFO. The last parameter of a function gets out first, i.e. LIFO,
# when many funnctions have been called in a recursion.
# recursion problems
# recursion and memoization
# Fibonacci series and memoization
# the stack overflow error
# stack overflow: when recursion, when the execution stack is full
# we use a while loop
while n != 0:
# d is the last digit
d = n % 2
# print(d)
stack1.insert(0, d)
# we remove the last digit
n = n // 2
# print the elements
for i in stack1:
print(i, end="")
print()
def toBinary(n):
if n == 0:
return
toBinary(n // 2)
print(n % 2, end='')
toBinary(14)
print()
toBinary(14)
print()
# d is the last digit
# d = n % 2
# stack1.insert(0, d)
# we remove the last digit
#n = n // 2
# we use base 8
def toOctal(n):
if n == 0:
return
toOctal(n // 8)
print(n % 8, end='')
# use base 10
def toDecimal(n):
if n == 0:
return
toDecimal(n // 10)
print(n % 10, end='')
# 453%10 = 3 = last digit
# 453//10 = 45 = remove last digit
# x%10 = last digit
# x//10 = remove last digit
# we use base 3
def toTernary(n):
if n == 0:
return
toTernary(n // 3)
print(n % 3, end='')
# sum of N numbers
def sumToN(N):
sum = 0
for i in range(1, N + 1):
sum += i
return sum
# recursion, sum of N numbers
def sumToN_rec(N):
#print(N)
if N == 1:
return 1
# return 1 + sumToN_rec(N-1)
return N + sumToN_rec(N - 1)
print('')
print(sumToN_rec(4))
#print(sumToN_rec(40000))
print(sumToN_rec(40))
# recursion problems
# coding recursion exercises
# programming recursion exercises
# recursion and memoization
# write code with and without recursion
# use one-line code
# lambda expressions => one line only
# comprehensions, list comprehensions => one line only
# use comprehensions: lists or generator objects
# comprehensions with "(.)" => generator objects
# generator objects are created for one time only
# generator objects => less memory, dynamic memory
# positional arguments
# define functions and call them with positional arguments
# positional arguments or non-positional arguments, default values
# default values go at the end, *args goes at the end
# use *args and **kwargs, **kwargs goes at the end
# use function1(*list1), use "*list1"
# we use "*list1" to break the list to its elements
# dictionary: keys and values
# dictionaries have keys and values
# we use *args and ** kwargs
# website: https://www.geeksforgeeks.org/args-kwargs-python/
# **kwargs => named arguments, dictionary
# dictionary has keys and values
# we use keys as an index to acccess the values
# "if "max" in dict1:": "max" is a key and not a value
# stack data structure => LIFO
# LIFO, last in first out, stack, execution stack
# recursion, memoization, execution stack, stack overflow
# limited stack, limited short execution stack
# Find the n-term of the series: a(n) = a(n-1)*2/3 with recursion and with no recursion.
# Compute the sum 1/2 + 3/5 + 5/8 + .... for N terms with recursion and with no recursion.
# numpy
import numpy
import numpy as np
# np.exp(a)/np.sum(np.exp(a))
# use: np.exp(a)/np.sum(np.exp(a))
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy.random
import scipy.stats as ss
from sklearn.mixture import GaussianMixture
import matplotlib
import matplotlib.pyplot as plt
import os
import tensorflow as tf
from sklearn import metrics
# UCI HAR Dataset
DATASET_PATH = "/Users/dionelisnikolaos/Downloads/UCI HAR Dataset/"
TRAIN = "train/"
TEST = "test/"
# Load "X" (the neural network's training and testing inputs)
# https://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition/blob/master/README.md
def load_X(X_signals_paths):
X_signals = []
for signal_type_path in X_signals_paths:
file = open(signal_type_path, 'r')
# Read dataset from disk, dealing with text files' syntax
X_signals.append(
[np.array(serie, dtype=np.float32) for serie in [
row.replace(' ', ' ').strip().split(' ') for row in file
]]
)
file.close()
return np.transpose(np.array(X_signals), (1, 2, 0))
INPUT_SIGNAL_TYPES = [
"body_acc_x_",
"body_acc_y_",
"body_acc_z_",
"body_gyro_x_",
"body_gyro_y_",
"body_gyro_z_",
"total_acc_x_",
"total_acc_y_",
"total_acc_z_"]
# Output classes to learn how to classify
LABELS = [
"WALKING",
"WALKING_UPSTAIRS",
"WALKING_DOWNSTAIRS",
"SITTING",
"STANDING",
"LAYING"]
X_train_signals_paths = [DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES]
X_test_signals_paths = [DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES]
X_train = load_X(X_train_signals_paths)
X_test = load_X(X_test_signals_paths)
# Load "y" (the neural network's training and testing outputs)
def load_y(y_path):
file = open(y_path, 'r')
# Read dataset from disk, dealing with text file's syntax
y_ = np.array(
[elem for elem in [
row.replace(' ', ' ').strip().split(' ') for row in file
]],
dtype=np.int32
)
file.close()
# Substract 1 to each output class for friendly 0-based indexing
return y_ - 1
y_train_path = DATASET_PATH + TRAIN + "y_train.txt"
y_test_path = DATASET_PATH + TEST + "y_test.txt"
y_train = load_y(y_train_path)
y_test = load_y(y_test_path)
# Input Data
training_data_count = len(X_train) # 7352 training series (with 50% overlap between each serie)
test_data_count = len(X_test) # 2947 testing series
n_steps = len(X_train[0]) # 128 timesteps per series
n_input = len(X_train[0][0]) # 9 input parameters per timestep
print('')
print(X_train.shape)
print(X_test.shape)
print('')
print(y_train.shape)
print(y_test.shape)
print('')
print(y_train)
print('')
print(y_test)
print('')
print(X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test))
print('')
print("Some useful info to get an insight on dataset's shape and normalisation:")
print("(X shape, y shape, every X's mean, every X's standard deviation)")
print('')
print(X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test))
print('')
phi_i = 1/7
mu_1 = [0.0, 1.0]
mu_2 = [0.75, 0.6]
mu_3 = [1.0, 0.0]
mu_4 = [0.45, -0.8]
mu_5 = [-0.45, -0.8]
mu_6 = [-0.95, -0.2]
mu_7 = [-0.8, 0.65]
mu_total = [mu_1, mu_2, mu_3, mu_4, mu_5, mu_6, mu_7]
sigmaSquared_i = 0.01*np.eye(2)
def prob21(x):
prob = 0.0
x = np.transpose(x)
#print(x)
#print(np.transpose(x))
#print(phi_i)
#print(phi_i)
#print((np.linalg.inv(sigmaSquared_i)) )
#print((np.linalg.det(sigmaSquared_i)))
for i in range(7):
#prob = prob + (phi_i * ((1 / np.sqrt(((2*np.pi)**7)*(np.linalg.det(sigmaSquared_i)))) * np.exp(-0.5*np.transpose(x-np.transpose(mu_total[i]))*(np.linalg.inv(sigmaSquared_i))*(x-np.transpose(mu_total[i])))))
#prob = prob + (phi_i * ((1 / np.sqrt(((2*np.pi)**7)*(np.linalg.det(sigmaSquared_i)))) * np.exp(-0.5*(np.transpose(x-np.transpose(mu_total[i])))*(np.linalg.inv(sigmaSquared_i))*((x-np.transpose(mu_total[i]))))))
#print(mu_total[i])
#prob = prob + (phi_i * ((1 / np.sqrt(((2 * np.pi) ** 7) * (np.linalg.det(sigmaSquared_i)))) * np.exp(-0.5 * ((x - (mu_total[i]))) * (np.linalg.inv(sigmaSquared_i)) * (np.transpose(x - (mu_total[i]))))))
var1 = ((x - (mu_total[i])))
var1 = np.array(var1)
#print((1 / np.sqrt(((2 * np.pi) ** 7) * (np.linalg.det(sigmaSquared_i)))))
#prob = prob + (phi_i * ((1 / np.sqrt(((2 * np.pi) ** 7) * (np.linalg.det(sigmaSquared_i)))) * np.exp(
# -0.5 * (((var1)) * (np.linalg.inv(sigmaSquared_i)) * ((var1.T))))))
#prob = prob + (phi_i * ((1 / np.sqrt(((2 * np.pi) ** 7) * (np.linalg.det(sigmaSquared_i)))) * np.exp(
# -0.5 * (((var1.T).dot((np.linalg.inv(sigmaSquared_i)))).dot(var1)))))
prob = prob + (phi_i * ((1 / np.sqrt(((2 * np.pi) ** 7) * (np.linalg.det(sigmaSquared_i)))) * np.exp(
-0.5 * (((var1).dot((np.linalg.inv(sigmaSquared_i)))).dot(var1)))))
return prob
#prob21([1.0, 0.0])
print(prob21([1.0, 0.0]))
print(prob21([0.0, 1.0]))
print(prob21([0.0, 0.0]))
# numpy
import numpy
import numpy as np
import seaborn as sns; sns.set()
from sklearn.mixture import GaussianMixture
#X = GMMSamples(W, mu, sigma, d)
#gmm = GMM(110, covariance_type='full', random_state=0)
import numpy.random
import scipy.stats as ss
import matplotlib
import matplotlib.pyplot as plt
import os
import tensorflow as tf
from sklearn import metrics
# UCI HAR Dataset
DATASET_PATH = "/Users/dionelisnikolaos/Downloads/UCI HAR Dataset/"
TRAIN = "train/"
TEST = "test/"
# Load "X" (the neural network's training and testing inputs)
def load_X(X_signals_paths):
X_signals = []
for signal_type_path in X_signals_paths:
file = open(signal_type_path, 'r')
# Read dataset from disk, dealing with text files' syntax
X_signals.append(
[np.array(serie, dtype=np.float32) for serie in [
row.replace(' ', ' ').strip().split(' ') for row in file
]]
)
file.close()
return np.transpose(np.array(X_signals), (1, 2, 0))
INPUT_SIGNAL_TYPES = [
"body_acc_x_",
"body_acc_y_",
"body_acc_z_",
"body_gyro_x_",
"body_gyro_y_",
"body_gyro_z_",
"total_acc_x_",
"total_acc_y_",
"total_acc_z_"]
# Output classes to learn how to classify
LABELS = [
"WALKING",
"WALKING_UPSTAIRS",
"WALKING_DOWNSTAIRS",
"SITTING",
"STANDING",
"LAYING"]
X_train_signals_paths = [DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES]
X_test_signals_paths = [DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES]
X_train = load_X(X_train_signals_paths)
X_test = load_X(X_test_signals_paths)
# Load "y" (the neural network's training and testing outputs)
def load_y(y_path):
file = open(y_path, 'r')
# Read dataset from disk, dealing with text file's syntax
y_ = np.array(
[elem for elem in [
row.replace(' ', ' ').strip().split(' ') for row in file
]],
dtype=np.int32
)
file.close()
# Substract 1 to each output class for friendly 0-based indexing
return y_ - 1
y_train_path = DATASET_PATH + TRAIN + "y_train.txt"
y_test_path = DATASET_PATH + TEST + "y_test.txt"
y_train = load_y(y_train_path)
y_test = load_y(y_test_path)
# Input Data
training_data_count = len(X_train) # 7352 training series (with 50% overlap between each serie)
test_data_count = len(X_test) # 2947 testing series
n_steps = len(X_train[0]) # 128 timesteps per series
n_input = len(X_train[0][0]) # 9 input parameters per timestep
print('')
print(X_train.shape)
print(X_test.shape)
print('')
print(y_train.shape)
print(y_test.shape)
# LSTM Neural Network's internal structure
n_hidden = 32 # Hidden layer num of features
n_classes = 6 # Total classes (should go up, or should go down)
# Training
learning_rate = 0.0025
lambda_loss_amount = 0.0015
training_iters = training_data_count * 300 # Loop 300 times on the dataset
batch_size = 1500
display_iter = 30000 # To show test set accuracy during training
print('')
print(X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test))
print('')
print("Some useful info to get an insight on dataset's shape and normalisation:")
print("(X shape, y shape, every X's mean, every X's standard deviation)")
print(X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test))
print('')
# use LSTM
def LSTM_RNN(_X, _weights, _biases):
# Function returns a tensorflow LSTM (RNN) artificial neural network from given parameters.
# Moreover, two LSTM cells are stacked which adds deepness to the neural network.
# Note, some code of this notebook is inspired from an slightly different
# RNN architecture used on another dataset, some of the credits goes to
# "aymericdamien" under the MIT license.
# (NOTE: This step could be greatly optimised by shaping the dataset once
# input shape: (batch_size, n_steps, n_input)
_X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size
# Reshape to prepare input to hidden activation
_X = tf.reshape(_X, [-1, n_input])
# new shape: (n_steps*batch_size, n_input)
# ReLU activation, thanks to Yu Zhao for adding this improvement here:
_X = tf.nn.relu(tf.matmul(_X, _weights['hidden']) + _biases['hidden'])
# Split data because rnn cell needs a list of inputs for the RNN inner loop
_X = tf.split(_X, n_steps, 0)
# new shape: n_steps * (batch_size, n_hidden)
# Define two stacked LSTM cells (two recurrent layers deep) with tensorflow
lstm_cell_1 = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
lstm_cell_2 = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
lstm_cells = tf.contrib.rnn.MultiRNNCell([lstm_cell_1, lstm_cell_2], state_is_tuple=True)
# Get LSTM cell output
outputs, states = tf.contrib.rnn.static_rnn(lstm_cells, _X, dtype=tf.float32)
# Get last time step's output feature for a "many-to-one" style classifier,
# as in the image describing RNNs at the top of this page
lstm_last_output = outputs[-1]
# Linear activation
return tf.matmul(lstm_last_output, _weights['out']) + _biases['out']
def extract_batch_size(_train, step, batch_size):
# Function to fetch a "batch_size" amount of data from "(X|y)_train" data.
shape = list(_train.shape)
shape[0] = batch_size
batch_s = np.empty(shape)
for i in range(batch_size):
# Loop index
index = ((step-1)*batch_size + i) % len(_train)
batch_s[i] = _train[index]
return batch_s
def one_hot(y_, n_classes=n_classes):
# Function to encode neural one-hot output labels from number indexes
# e.g.:
# one_hot(y_=[[5], [0], [3]], n_classes=6):
# return [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]
y_ = y_.reshape(len(y_))
return np.eye(n_classes)[np.array(y_, dtype=np.int32)] # Returns FLOATS
# https://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition/blob/master/README.md
# use: https://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition/blob/master/README.md
# Graph input/output
x = tf.placeholder(tf.float32, [None, n_steps, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
# Graph weights
weights = {
'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights
'out': tf.Variable(tf.random_normal([n_hidden, n_classes], mean=1.0))
}
biases = {
'hidden': tf.Variable(tf.random_normal([n_hidden])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
pred = LSTM_RNN(x, weights, biases)
# Loss, optimizer and evaluation
l2 = lambda_loss_amount * sum(
tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()
) # L2 loss prevents this overkill neural network to overfit the data
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) + l2 # Softmax loss
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# To keep track of training's performance
test_losses = []
test_accuracies = []
train_losses = []
train_accuracies = []
# Launch the graph
sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True))
init = tf.global_variables_initializer()
sess.run(init)
# Perform Training steps with "batch_size" amount of example data at each loop
step = 1
while step * batch_size <= training_iters:
batch_xs = extract_batch_size(X_train, step, batch_size)
batch_ys = one_hot(extract_batch_size(y_train, step, batch_size))
# Fit training using batch data
_, loss, acc = sess.run(
[optimizer, cost, accuracy],
feed_dict={
x: batch_xs,
y: batch_ys
}
)
train_losses.append(loss)
train_accuracies.append(acc)
# Evaluate network only at some steps for faster training:
if (step*batch_size % display_iter == 0) or (step == 1) or (step * batch_size > training_iters):
# To not spam console, show training accuracy/loss in this "if"
print("Training iter #" + str(step*batch_size) + \
": Batch Loss = " + "{:.6f}".format(loss) + \
", Accuracy = {}".format(acc))
# Evaluation on the test set (no learning made here - just evaluation for diagnosis)
loss, acc = sess.run(
[cost, accuracy],
feed_dict={
x: X_test,
y: one_hot(y_test)
}
)
test_losses.append(loss)
test_accuracies.append(acc)
print("PERFORMANCE ON TEST SET: " + \
"Batch Loss = {}".format(loss) + \
", Accuracy = {}".format(acc))
step += 1
print("Optimization Finished!")
# Accuracy for test data
one_hot_predictions, accuracy, final_loss = sess.run(
[pred, accuracy, cost],
feed_dict={
x: X_test,
y: one_hot(y_test)
}
)
test_losses.append(final_loss)
test_accuracies.append(accuracy)
print("FINAL RESULT: " + \
"Batch Loss = {}".format(final_loss) + \