-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathprogram1_Torch.py
3277 lines (2217 loc) · 84.8 KB
/
program1_Torch.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
# main website: http://interactivepython.org/runestone/static/pythonds/index.html#
# we use: http://interactivepython.org/runestone/static/pythonds/Recursion/toctree.html
# use: https://docs.python.org/3/library/functions.html
# we use the Python built-in functions
# https://docs.python.org/3/library/functions.html
# we use PyTorch
import torch
# use numpy
import numpy as np
# create a tensor
x = torch.Tensor([1, 2, 3])
print(x)
x = torch.Tensor([[1, 2],
[5, 3]])
print(x)
x = torch.Tensor([[[1, 2],
[5, 3]],
[[5,3],
[6,7]]])
#print(x)
print(x[0][1])
# layer, row, column
# we are indexing tensors
# indexing tensor: layer row, column
print(x[0][1])
# indexing tensor: layer row, column
print(x[0][1][0])
# a variable is different from tensors
# tensors is values
# variables has values that change
# we use Variable
from torch.autograd import Variable
# n is the number of features
n = 2
# m is the number of training points
m = 300
# m is the number of training samples, m>>n
# randn(.,.) is Gaussian with zero-mean and unit variance
# we create a matrix of depth n and breadth m
x = torch.randn(n, m)
# Variable
X = Variable(x)
# we create a fake data set, we create Y
# we use: X.data[0,:], where this is the first row of the matrix X
# we use: X.data[1,:], where this is the second row of the matrix X
Y = Variable(2*X.data[0,:] + 6*X.data[1,:] + 10)
w = Variable(torch.randn(1,2), requires_grad=True)
b = Variable(torch.randn([1]), requires_grad=True)
costs = []
#import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.ion()
#plt.figure()
fig = plt.figure()
ax1 = fig.add_subplot(111, projection="3d")
ax1.scatter(X[0,:].data, X[1,:].data, Y.data)
plt.show()
#matplotlib.pyplot.show()
#plt.pause(9999999999)
#plt.pause(2)
plt.pause(1)
#epochs = 500
#epochs = 100
# define the number of epochs
epochs = 10
# learning rate lr
#lr = 0.5
lr = 0.1
#import numpy as np
#x1 = np.arange(-2, 10)
#x1 = np.arange(100)
x1 = np.arange(-2, 4)
#x2 = np.arange(-2, 10)
#x2 = np.arange(100)
x2 = np.arange(-2, 4)
x1, x2 = np.meshgrid(x1, x2)
# training
for epoch in range(epochs):
h = torch.mm(w, X) + b
cost = torch.sum(0.5*(h-Y)**2)/m
# to the power of 2, we use: ** 2
cost.backward()
w.data -= lr * w.grad.data
b.data -= lr * b.grad.data
w.grad.data.zero_()
# the underscore _ means replace it with zero
b.grad.data.zero_()
# the underscore _ means replace it with zero
costs.append(cost.data)
y = b.data[0] + x1*w.data[0][0] + x2*w.data[0][1]
s = ax1.plot_surface(x1, x2, y)
fig.canvas.draw()
s.remove()
plt.pause(1)
# use: https://docs.python.org/3/library/functions.html
# we use the Python built-in functions
# https://docs.python.org/3/library/functions.html
# main website: http://interactivepython.org/runestone/static/pythonds/index.html#
# we use: http://interactivepython.org/runestone/static/pythonds/Recursion/toctree.html
import numpy as np
# find the number of even numbers in the list
a = [4, 5, 6, 5, 6, 7, 6, 5, 4, 5, 6]
counter0 = 0
for i in a:
if i % 2 == 0:
counter0 += 1
print('')
print(counter0)
def counter1(list1):
count1 = 0
for i in list1:
if i % 2 == 0:
count1 += 1
return count1
print(counter1(a))
# find how many elements in b exist in a
b = [1, 2, 3, 5]
def counter2(list1, list2):
count1 = 0
for i in list2:
for j in list1:
if i == j:
count1 += 1
break
return count1
print('')
print(counter2(a, b))
# find how many elements in b exist in a
b = [-1, 0, 2, 3, 5, 6]
print(counter2(a, b))
# find how many double entries exist in a list
def counter3(list1):
# list2 = list(set(list1))
list2 = set(list1)
return len(list1) - len(list2)
print('')
print(counter3(a))
# find how many double entries exist in a list
def counter4(list1):
count1 = 0
for i in range(len(list1)):
if list1[i] not in list1[:i]:
for j in range(i + 1, len(list1)):
if list1[i] == list1[j]:
count1 += 1
break
return count1
# we have used: "if list1[i] not in list1[:i]:"
# "if a[i] not in a[:i]:"
# use: "if list1[i] not in list1[:i]:"
print(counter4(a))
print('')
a = [4, 5, 6, 5, 6, 7, 6, 5, 4, 5, 6]
# a[:i] is the same as a[0:i:1]
# we now use "if a[i] not in a[:i]:"
for i in range(len(a)):
if a[i] not in a[:i]:
print(a[i])
# use LIST COMPREHENSION
# we use: https://docs.python.org/3/library/functions.html
# find how many numbers are even using list comprehension
a = [3,4,5,4,5,6,7,8,9]
# we use list comprehensions
b = len([k for k in a if k % 2 == 0])
print('')
print(b)
b = [k for k in a if k % 2 == 0]
print(b)
b = [k**2 for k in a if k % 2 == 0]
print(b)
# use generator objects
b = (k**2 for k in a if k % 2 == 0 and k % 4 == 0)
print(list(b))
# list comprehensions in parenthesis => generator object
# we use generator objects instead of lists
# generator object are from list comprehensions in parenthesis
print('')
# we use generator objects
b = (k**3 for k in a if k % 2 == 0 and k % 4 == 0)
print(b)
# generator objects give us their values when we call them with a for loop
# generator objects give us their values only once
# a generator object gives us its values only one time when we use a for loop
# use a for loop for generator objects
for i in b:
print (i)
# this will produce nothing due to the generator object
for i in b:
print (i)
# create a generator object
b = (k**3 for k in a if k % 2 == 0 and k % 4 == 0)
# use dynamic memory with the generator object
print('')
# use "list(.)"
print(list(b))
# we filter a list and produce a new list
c = ((k, k+1) for k in a)
# we use tuples: we create a list of tuples
print('')
print(list(c))
# filter the list and produce a new list
c = ((k, k/2) for k in a)
print(list(c))
# "/2" is float division and "//2" is integer division
c = ((k, k//2) for k in a)
print(list(c))
# list comprehention: filter kai map
d = ('x'*k for k in a)
# "'x'*k" means repeat 'x' k times
print('')
print(list(d))
# "*i" means repeat i times
d = ('x'*i for i in a if i%2 == 1)
print(list(d))
print('')
a = [3,4,5,4,5,6,7,8,9]
# use: "if a[i] not in a[:i]"
d = ('o'*a[i] for i in range(len(a)) if a[i] not in a[:i])
print(list(d))
# filter and map
# map because we create a new list or generator object
# use "set(list1)" for no dublicates
# build-in functions: https://docs.python.org/3/library/functions.html
# list comprehentions perform filtering kai mapping
list1 = [1,2,3]
list2 = ("a", "b", "c")
# list with tuples with all combinations of 1 και 2
list3 = set((i,j) for i in list1 for j in list2)
print('')
print(list3)
list3 = set((i,j) for i in list1 for j in list2 if i % 2 == 0)
print(list3)
print('')
list2 = ("a", "", "c")
list3 = set((i,j) for i in list1 for j in list2 if i % 2 == 0 and len(j) > 0)
print(list3)
list3 = [2,4,-1,-2,2,2,8,1,8]
list4 = set(i for i in list1 for j in list3 if i==j)
print(list(list4))
list3 = [2,4,-1,-2,2,2,8,1,8]
#list4 = [i for i in list1 for j in list3 if i==j]
# use: if list1[i] not in list1[:i]
list4 = [list1[i] for i in range(len(list1)) for j in range(len(list3)) if list1[i] not in list1[:i] and \
list3[j] not in list3[:j] and list1[i]==list3[j]]
print(list4)
# list comprehentions perform both filtering kai mapping
# use list comprehension
list1 = [-4, 4, -3, -5, 2, -1, 9]
list2 = [k**2 for k in list1]
print('')
print(list1)
print(list2)
# use list comprehention for filtering kai mapping
list2 = [(abs(k)+1)**2 for k in list1 if k%2 == 0]
print(list2)
# built-in functions: all, any
# any: return true when at least one element is true
# built-in functions: all, any
# all: return false when at least one element is false
# check if negative number exists
any(p<0 for p in a)
print('')
print(any(p<0 for p in a))
print(not all(p>=0 for p in a))
# check if x exists in the list
x = 8
print('')
#any(i==x for i in a)
print(any(i==x for i in a))
x = 100
print(any(i==x for i in a))
# we sort the list
# use either "sorted" or "sort"
# we use either "sorted" or "sort"
# "sorted" return a new list that is sorted
# "sort" sorts the list itself (not creating a new list)
print('')
a = [3, 4, -3, 2, -3, -4, 3, 31]
b = sorted(a)
a.sort()
print(a)
print(b)
# we use either "sorted" or "sort"
# "sorted": parameter reverse
a = [3, 4, -3, 2, -3, -4, 3, 31]
b = sorted(a, reverse=True)
print(b)
print('')
# "sorted": parameter key
# the parameter key is a function or a lambda expression
# we use lambda expressions
b = sorted(a, reverse=True, key=abs)
print(b)
# "sorted": parameter key is either a function or a lambda expression
# "sorted": use a function or a lambda expression
# sorting is based on the result of the function or the lambda expression
# define a function for the "sorted" parameter key
def myfunction(k):
if k % 2 == 0:
return k
else:
return k ** 2
a = [3, 4, -3, 2, -3, -4, 3, 31]
c = a
b = sorted(a, reverse=True, key=myfunction)
print('')
print(b)
# key functions can be any one-to-one function
# use: lamda parameters : return_value
# lamda expression in Python: "lamda parameters : return_value"
# use: x if x >= 0 else -x
# we can use if in lambda expressions: "x if x >= 0 else -x"
# sorting with -x
b = sorted(a, key=lambda x: -x)
# lambda expression: "lambda x: -x"
print('')
print(b)
# sorting with abs
b = sorted(a, key=abs)
print(b)
# use the previously defined function "my function"
# we use lamda expression for "my function"
b = sorted(a, key=lambda k: k if k % 2 == 0 else k ** 2)
print('')
print(b)
# we use lamda expression and if statement
b = sorted(a, key=lambda k: k if k % 4 == 0 else k ** 3)
print(b)
# we define function that has a function as a parameter
def myfunction2(list1, function1):
for i in list1:
function1(i)
print('')
myfunction2(a, print) # print every value
print('')
# myfunction2(sorted(a), lambda x : print(-x+y))
myfunction2(sorted(a), lambda x: print(-x))
print('')
myfunction2(a, lambda x: print(x if x % 2 == 0 else x ** 2))
# we have use lambda expressions
# binary search requires a sorted list
# binary search uses "==", ">" and "<" than middle element
# website: http://interactivepython.org/runestone/static/pythonds/index.html#
# we use integer division: "//2"
# binary search uses "first", "last" and "middle = (first+last)//2"
# binary search: "ceiling", "floor" and both the ceiling and the floor move
# binary search needs only maximum 9 or 10 searches => very efficient, very fast, very stable
# functions use global variables
# global vs local memory variables
# def funName(localVar1, localVar2): global x,y
# we use: "if array1[i] not in array1[:i]:"
# use: "for i in array1:" and "for i in range(len(array1)):"
# use "help(list)"
array1 = [2, 5, 6, 3, 2, 2, 1, -1, 7]
array1.sort()
print('')
print(array1)
# we use straight exchange sort
# straight exchange sort = babble sort
# http://interactivepython.org/runestone/static/pythonds/index.html#
# babble sort uses swap: "x,y = y,x"
# swap: "x[i], x[i-1] = x[i-1], x[i]"
# babble sort has 2 for loops and a swap operation
# we use "if list1[i] not in list1[:i]:" when "for i in range(len(list1)):"
# use len(list1), sum(list1), set(list1) and list(set(list1))
# use list comprehension
array2 = [i**3 for i in array1 if i%2 == 0]
print(array2)
# create a generator object
# less memory, dynamic memory, use "(.)" and not "[.]"
array2 = (i**3 for i in array1 if i%2 == 0)
print('')
print(list(array2))
# generator objects exist for only one time
print(list(array2))
# perform both filtering and mapping
# we filter and map using list comprehensions
array2 = [(i, i+1) for i in array1]
print('')
print(array1)
print(array2)
array2 = [(i, i/2) for i in array1]
print(array2)
# buil-in functions: all(.), any(.), filter(.), sorted(.)
# use the buil-in function "sorted(.)"
array1 = [2, 5, 6, 3, 2, 2, 1, -1, 7]
array2 = sorted(array1, reverse = True)
print('')
print(array2)
# we now use lambda expressions
# lambda expressions are small def functions
# use lambda expressions
array2 = sorted(array1, reverse = False, key = lambda x : -x)
print(array2)
# we use lambda expressions in Python
array2 = sorted(array1, reverse = False, key = lambda input1 : input1 if input1%2 == 0 else input1+501)
print(array2)
from numpy import nan
# we use an if statement and a lambda expression
array2 = sorted(array1, reverse = False, key = lambda x : x if x%2 == 1 else nan)
print(array2)
# map(.) and filter(.) build-in functions
# for build-in functions: https://docs.python.org/3/library/functions.html
print('')
# use the map(.) build-in function
print(list(map(myfunction, array1)))
print(list(map(lambda x : -x**2, array1)))
# 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 os
import tensorflow as tf
from sklearn import metrics
# https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
from gluoncv.data import ImageNet
from mxnet.gluon.data import DataLoader
from mxnet.gluon.data.vision import transforms
from gluoncv import data, utils
from matplotlib import pyplot as plt
import scipy.io as sio
import matplotlib.pyplot as plt
# index
image_ind = 10
#train_data = sio.loadmat('train_32x32.mat')
train_data = sio.loadmat('/Users/dionelisnikolaos/Downloads/train_32x32.mat')
# SVHN Dataset
# Street View House Numbers (SVHN)
# access to the dict
x_train = train_data['X']
y_train = train_data['y']
# show sample
plt.imshow(x_train[:,:,:,image_ind])
plt.show()
print(y_train[image_ind])
image_ind = 10 # index, image index
test_data = sio.loadmat('/Users/dionelisnikolaos/Downloads/test_32x32.mat')
# access to the dict
x_test = test_data['X']
y_test = test_data['y']
# show sample
plt.imshow(x_test[:,:,:,image_ind])
plt.show()
print(y_test[image_ind])
# 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('')
# http://www.ee.imperial.ac.uk/hp/staff/dmb/voicebox/mdoc/v_mfiles/v_gaussmixp.html
# use: http://www.ee.imperial.ac.uk/hp/staff/dmb/voicebox/mdoc/v_mfiles/v_gaussmixp.html
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)
# we use: http://www.ee.imperial.ac.uk/hp/staff/dmb/voicebox/mdoc/v_mfiles/v_gaussmixp.html
# v_gaussmixp([], [[0, 1]; [0.75, 0.70]; [1, 0]; [0.48, -0.8]; [-0.48, -0.8]; [-1, -0.24]; [-0.8, 0.6]], [[0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]], [1, 1, 1, 1, 1, 1, 1]')
# use: v_gaussmixp([], [[0, 1]; [0.75, 0.70]; [1, 0]; [0.48, -0.8]; [-0.48, -0.8]; [-1, -0.24]; [-0.8, 0.6]], [[0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]], [1, 1, 1, 1, 1, 1, 1]')
# find GMM probability
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]))))))
#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(mu_total[i])
#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]))
# http://www.ee.imperial.ac.uk/hp/staff/dmb/voicebox/mdoc/v_mfiles/v_gaussmixp.html
# we use: http://www.ee.imperial.ac.uk/hp/staff/dmb/voicebox/mdoc/v_mfiles/v_gaussmixp.html
# v_gaussmixp([], [[0, 1]; [0.75, 0.70]; [1, 0]; [0.48, -0.8]; [-0.48, -0.8]; [-1, -0.24]; [-0.8, 0.6]], [[0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]; [0.05, 0.05]], [1, 1, 1, 1, 1, 1, 1]')
# v_gaussmixp([], [[0, 1]; [0.75, 0.70]; [1, 0]; [0.48, -0.8]; [-0.48, -0.8]; [-1, -0.24]; [-0.8, 0.6]], [[0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]; [0.01, 0.01]], [1, 1, 1, 1, 1, 1, 1]')
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/"
# we use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
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)