-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
MatrixExtend.mqh
1664 lines (1347 loc) · 52.2 KB
/
MatrixExtend.mqh
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
//+------------------------------------------------------------------+
//| matrix_utils.mqh |
//| Copyright 2022, Omega Joctan . |
//| https://www.mql5.com/en/users/omegajoctan |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, Omega Joctan"
#property link "https://www.mql5.com/en/users/omegajoctan"
#include <MALE5\preprocessing.mqh>
//+------------------------------------------------------------------+
//| A class containing additional matrix manipulation functions |
//+------------------------------------------------------------------+
class MatrixExtend
{
protected:
template<typename T>
static T MathRandom(T mini, T maxi);
static string CalcTimeElapsed(double seconds);
static void Swap(double &var1, double &var2);
static string ConvertTime(double seconds);
template<typename T>
static void GetCol(const T &Matrix[], T &Col[], int column, int cols);
static bool IsNumber(string text);
static vector FixColumn(CLabelEncoder &encoder, string &Arr[], double threshold =0.3);
public:
MatrixExtend(void);
~MatrixExtend(void);
template<typename T>
static int Sign(T var)
{
if (var<0)
return -1;
else if (var==0)
return 0;
else
return 1;
}
//--- File Functions
template <typename T>
static bool WriteCsv(string csv_name, matrix<T> &matrix_, string &header[] ,bool common=false, int digits=5);
template <typename T>
static bool WriteCsv(string csv_name, matrix<T> &matrix_, string header_string="",bool common=false, int digits=5);
static matrix ReadCsv(string file_name, string &headers, string delimiter=",",bool common=false, bool auto_encode=false);
static matrix DBtoMatrix(int db_handle, string table_name,string &column_names[],int total=WHOLE_ARRAY);
static bool write_bin(vector &v, string file);
//--- Manipulations
template<typename T>
static bool RemoveCol(matrix<T> &mat, ulong col);
static void RemoveMultCols(matrix &mat, int &cols[]);
static void RemoveMultCols(matrix &mat, int from, int total=WHOLE_ARRAY);
static void RemoveRow(matrix &mat,ulong row);
static void VectorRemoveIndex(vector &v, ulong index);
//--- Machine Learning
template<typename T>
static bool XandYSplitMatrices(const matrix<T> &matrix_, matrix<T> &xmatrix, vector<T> &y_vector,int y_column=-1);
template <typename T>
static void TrainTestSplitMatrices(const matrix<T> &X, const vector<T> &y, matrix<T> &x_train, vector<T> &y_train, matrix<T> &x_test, vector<T> &y_test, double train_size=0.7,int random_state=-1, bool shuffle=true);
static matrix DesignMatrix(matrix &x_matrix);
static matrix OneHotEncoding(const vector &v); //ONe hot encoding
static matrix Sign(matrix &x);
static vector Sign(vector &x);
static matrix eye(uint num_features);
//--- Detection
static void Unique(const string &Array[], string &classes_arr[]);
static vector Unique(const vector &v); //Identifies classes available in a vector
static vector Unique_count(vector &v);
template<typename T>
static vector Random(T min, T max, int size,int random_state=-1); //Generates a random vector of type T sized = size
static matrix Random(double min, double max, ulong rows, ulong cols, int random_state=-1);
template<typename T>
static vector Search(const vector<T> &v, T value);
//--- Transformations
static matrix VectorToMatrix(const vector &v, ulong cols=1);
template<typename T>
static vector MatrixToVector(const matrix<T> &mat);
template<typename T>
static vector ArrayToVector(const T &Arr[]);
template<typename T>
static bool VectorToArray(const vector<T> &v,T &arr[]);
//--- Manipulations
static vector concatenate(const vector &v1, const vector &v2); //Appends v2 to vector 1
static matrix concatenate(const matrix &mat1, const matrix &mat2, int axis = 0);
template<typename T>
static matrix<T> concatenate(const matrix<T> &mat, const vector<T> &v, int axis=1);
template<typename T>
static bool Copy(const vector<T> &src, vector<T> &dst, ulong src_start,ulong total=WHOLE_ARRAY);
template<typename T>
static void Reverse(vector<T> &v);
template<typename T>
static void Reverse(matrix<T> &mat);
static matrix HadamardProduct(matrix &a, matrix &b);
template<typename T>
static void Randomize(vector<T> &v, int random_state=-1, bool replace=false);
template<typename T>
static void Randomize(matrix<T> &matrix_,int random_state=-1, bool replace=false);
template<typename T>
static void NormalizeDouble_(vector<T> &v, int digits=3);
template<typename T>
static void NormalizeDouble_(matrix<T> &mat, int digits=3);
static int CopyBufferVector(int handle, int buff_num, int start_pos,int count, vector &v);
static string Stringfy(vector &v, int digits = 2);
static matrix Zeros(ulong rows, ulong cols) { matrix ret_mat(rows, cols); return(ret_mat.Fill(0.0)); }
static vector Zeros(ulong size) { vector ret_v(size); return( ret_v.Fill(0.0)); }
static matrix Get(const matrix &mat, ulong start_index, ulong end_index);
static vector Get(const vector &v, ulong start_index, ulong end_index);
template<typename T>
static vector Sort(vector<T> &v,ENUM_SORT_MODE sort_mode=SORT_ASCENDING);
template<typename T>
static vector ArgSort(vector<T> &v);
static matrix Slice(const matrix &mat, ulong start_index, int end_index, uint axis=0);
static vector Slice(const vector &vec, ulong start_index, int end_index);
//--- Others
static void PrintShort(matrix &matrix_,ulong rows=5, int digits=5);
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
MatrixExtend::MatrixExtend(void)
{
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
MatrixExtend::~MatrixExtend(void)
{
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
matrix MatrixExtend::VectorToMatrix(const vector &v, ulong cols=1)
{
ulong rows = 0;
matrix mat = {};
if ( v.Size() % cols > 0) //If there is a reminder
{
printf("Invalid rows %d and cols %d for this vector size ",rows,v.Size()/cols);
return mat;
}
else
rows = v.Size()/cols;
//---
mat.Resize(rows, cols);
for(ulong i=0, index =0; i<rows; i++)
for(ulong j=0; j<cols; j++, index++)
{
mat[i][j] = v[index];
}
return(mat);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
vector MatrixExtend::MatrixToVector(const matrix<T> &mat)
{
vector<T> v = {};
matrix<T> temp_mat = mat;
if (!temp_mat.Swap(v))
Print(__FUNCTION__," Failed to turn the matrix[",mat.Rows(),"x",mat.Cols(),"] into a vector");
return(v);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
bool MatrixExtend::RemoveCol(matrix<T> &mat, ulong col)
{
matrix<T> new_matrix(mat.Rows(),mat.Cols()-1); //Remove the one Column
if (col > mat.Cols())
{
Print(__FUNCTION__," column out of range");
return false;
}
for (ulong i=0, new_col=0; i<mat.Cols(); i++)
{
if (i == col)
continue;
else
{
new_matrix.Col(mat.Col(i),new_col);
new_col++;
}
}
mat.Copy(new_matrix);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void MatrixExtend::RemoveMultCols(matrix &mat, int &cols[])
{
ulong size = (int)ArraySize(cols);
if(size > mat.Cols())
{
Print(__FUNCTION__," Columns to remove can't be more than the available columns");
return;
}
vector Zeros(mat.Rows());
Zeros.Fill(0);
for(ulong i=0; i<size; i++)
for(ulong j=0; j<mat.Cols(); j++)
{
if(cols[i] == j)
mat.Col(Zeros,j);
}
//---
vector column_vector;
while (mat.Cols()-size >= size)
for(ulong i=0; i<mat.Cols(); i++)
{
column_vector = mat.Col(i);
if(column_vector.Sum()==0)
if (!RemoveCol(mat,i))
{
printf("%s Line %d Failed to remove a column %d from a matrix",__FUNCTION__,__LINE__,i);
break;
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void MatrixExtend::RemoveMultCols(matrix &mat, int from, int total=WHOLE_ARRAY)
{
total = total==WHOLE_ARRAY ? (int)mat.Cols()-from : total;
if(total > (int)mat.Cols())
{
Print(__FUNCTION__," Columns to remove can't be more than the available columns");
return;
}
vector Zeros(mat.Rows());
Zeros.Fill(0);
for (int i=from; i<total+from; i++)
mat.Col(Zeros, i);
//---
ulong remain_size = mat.Cols()-total;
while (mat.Cols() >= remain_size && !IsStopped())
{
//printf("cols %d total %d",cols,total);
for(ulong i=0; i<mat.Cols(); i++) //loop the entire matrix searching for columns to remove
if(mat.Col(i).Sum()==0)
if (!RemoveCol(mat,i))
{
printf("%s Line %s Failed to remove a column %d from a matrix",__FUNCTION__,__LINE__,i);
break;
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void MatrixExtend::RemoveRow(matrix &mat,ulong row)
{
matrix new_matrix(mat.Rows()-1,mat.Cols()); //Remove the one Row
for(ulong i=0, new_rows=0; i<mat.Rows(); i++)
{
if(i == row)
continue;
else
{
new_matrix.Row(mat.Row(i),new_rows);
new_rows++;
}
}
mat.Copy(new_matrix);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void MatrixExtend::VectorRemoveIndex(vector &v, ulong index)
{
vector new_v(v.Size()-1);
for(ulong i=0, count = 0; i<v.Size(); i++)
if(i != index)
{
new_v[count] = v[i];
count++;
}
v.Copy(new_v);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template <typename T>
bool MatrixExtend::WriteCsv(string csv_name, matrix<T> &matrix_, string &header[], bool common=false, int digits=5)
{
string header_str = "";
for (int i=0; i<ArraySize(header); i++)
header_str += header[i] + ((i+1 == ArraySize(header)) ? "" : ",");
return WriteCsv(csv_name, matrix_, header_str, common, digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template <typename T>
bool MatrixExtend::WriteCsv(string csv_name, matrix<T> &matrix_, string header_string="", bool common=false, int digits=5)
{
FileDelete(csv_name);
int handle = FileOpen(csv_name,FILE_WRITE|FILE_CSV|FILE_ANSI|(common?FILE_COMMON:FILE_IS_WRITABLE),",",CP_UTF8);
if (header_string == "" || header_string == NULL)
for (ulong i=0; i<matrix_.Cols(); i++)
header_string += "None"+ (i==matrix_.Cols()-1?"":",");
if(handle == INVALID_HANDLE)
{
printf("Invalid %s handle Error %d ",csv_name,GetLastError());
return (false);
}
string concstring;
vector<T> row = {};
datetime time_start = GetTickCount(), current_time;
string header[];
ushort u_sep;
u_sep = StringGetCharacter(",",0);
StringSplit(header_string,u_sep, header);
vector<T> colsinrows = matrix_.Row(0);
if (ArraySize(header) != (int)colsinrows.Size())
{
printf("headers=%d and columns=%d from the matrix vary is size ",ArraySize(header),colsinrows.Size());
return false;
}
//---
string header_str = "";
for (int i=0; i<ArraySize(header); i++)
header_str += header[i] + (i+1 == colsinrows.Size() ? "" : ",");
FileWrite(handle,header_str);
FileSeek(handle,0,SEEK_SET);
for(ulong i=0; i<matrix_.Rows() && !IsStopped(); i++)
{
ZeroMemory(concstring);
row = matrix_.Row(i);
for(ulong j=0, cols =1; j<row.Size() && !IsStopped(); j++, cols++)
{
current_time = GetTickCount();
Comment("Writting ",csv_name," record [",i+1,"/",matrix_.Rows(),"] Time taken | ",ConvertTime((current_time - time_start) / 1000.0));
concstring += (string)NormalizeDouble(row[j],digits) + (cols == matrix_.Cols() ? "" : ",");
}
FileSeek(handle,0,SEEK_END);
FileWrite(handle,concstring);
}
FileClose(handle);
return (true);
}
//+------------------------------------------------------------------+
//| This Function is aimed at Detectin the Strings columns and it |
//| encodes them, while fixing the missing information in the column |
//+------------------------------------------------------------------+
vector MatrixExtend::FixColumn(CLabelEncoder &encoder, string &Arr[], double threshold =0.3)
{
int size = ArraySize(Arr);
int str_count =0;
vector ret(size);
for (int i=0; i<size; i++) //Check what percentage of data is strings
if (!IsNumber(Arr[i]))
str_count++;
//---
bool is_strings_col = (str_count>=size*threshold);
if (is_strings_col) //if a column is detected to be a column full of strings
{
//Encode it
return encoder.encode(Arr);;
}
//---
string value = "";
int total =0;
double mean=0;
for (int i=0; i<size; i++) //Detect Missing values | Remove the rows
{
value = Arr[i];
if (value == "NaN" || value == "-NaN" || value == "!VALUE" ||
value == "" || value == "NA" || value == "N/A" || value == "null" ||
value == "Inf" || value == "Infinity" || value == "-Inf" || value == "-Infinity" ||
value == "#DIV/0!" || value == "#VALUE!") //Check if there are NotANumber values
continue;
mean += (double)Arr[i];
total++;
}
mean /= total;
//---
for (int i=0; i<size; i++) //Detect Missing values | Remove the rows
{
value = Arr[i];
if (value == "NaN" || value == "-NaN" || value == "!VALUE" ||
value == "" || value == "NA" || value == "N/A" || value == "null" ||
value == "Inf" || value == "Infinity" || value == "-Inf" || value == "-Infinity" ||
value == "#DIV/0!" || value == "#VALUE!") //Check if there are NotANumber values
{
ret[i] = mean;
continue;
}
ret[i] = double(Arr[i]);
}
return ret;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool MatrixExtend::IsNumber(string text)
{
int length = StringLen(text); // Get the length of the string.
int pointcount = 0; // Initialize a counter for the number of decimal points.
// Iterate through each character in the text.
for (int i = 0; i < length; i++)
{
int char1 = StringGetCharacter(text, i); // Get the ASCII code of the current character.
// If the character is a decimal point, increment the decimal point counter.
if (char1 == 46)
pointcount += 1;
// If the character is a digit or a decimal point and the number of decimal points is less than 2,
// continue to the next character; otherwise, return false.
if (((char1 >= 48 && char1 <= 57) || char1 == 46) && pointcount < 2)
continue;
else
return false;
}
// If all characters in the text have been checked without returning false, return true.
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
matrix MatrixExtend::ReadCsv(string file_name, string &headers, string delimiter=",",bool common=false, bool auto_encode=false)
{
CLabelEncoder encoder;
string Arr[];
int all_size = 0;
int cols_total=0;
int handle = FileOpen(file_name,FILE_SHARE_READ|FILE_CSV|FILE_ANSI|(common?FILE_COMMON:FILE_ANSI),delimiter);
datetime time_start = GetTickCount(), current_time;
string header_arr[];
int header_column = 0;
if(handle == INVALID_HANDLE)
{
printf("Invalid %s handle Error %d ",file_name,GetLastError());
Print(GetLastError()==0?" TIP | File Might be in use Somewhere else or in another Directory":"");
}
else
{
int column = 0, rows=0;
while(!FileIsEnding(handle) && !IsStopped())
{
string data = FileReadString(handle);
//---
if(rows ==0)
{
header_column++;
ArrayResize(header_arr, header_column);
header_arr[header_column-1] = data;
}
column++;
if(rows>0) //Avoid the first column which contains the column's header
{
all_size++;
ArrayResize(Arr,all_size);
Arr[all_size-1] = data;
}
//---
if(FileIsLineEnding(handle))
{
cols_total=column;
rows++;
column = 0;
current_time = GetTickCount();
Comment("Reading ",file_name," record = ",rows," Time taken | ",ConvertTime((current_time - time_start) / 1000.0));
}
}
FileClose(handle);
}
//--- Get the headers
headers="";
for(uint i=0; i<header_arr.Size(); i++)
headers += header_arr[i] + ((i==header_arr.Size()-1) ? "" :delimiter);
//---
int rows =all_size/cols_total;
Comment("");
matrix mat(rows, cols_total);
string Col[];
vector col_vector;
for (int i=0; i<cols_total; i++)
{
GetCol(Arr, Col, i+1, cols_total);
col_vector = auto_encode ? FixColumn(encoder, Col) : ArrayToVector(Col);
mat.Col(col_vector, i);
}
return(mat);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
void MatrixExtend::GetCol(const T &Matrix[], T &Col[], int column, int cols)
{
int rows = ArraySize(Matrix)/cols;
ArrayResize(Col,rows);
int start = 0;
for (int i=0; i<cols; i++)
{
start = i;
if (i != column-1) continue;
else
for (int j=0; j<rows; j++)
{
//printf("ColMatrix[%d} Matrix{%d]",j,start);
Col[j] = Matrix[start];
start += cols;
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
vector MatrixExtend::ArrayToVector(const T &Arr[])
{
vector v(ArraySize(Arr));
for (int i=0; i<ArraySize(Arr); i++)
v[i] = double(Arr[i]);
return (v);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
bool MatrixExtend::VectorToArray(const vector<T> &v, T &arr[])
{
vector temp = v;
if (!temp.Swap(arr))
{
Print("Failed to Convert vector to Array Err=",GetLastError());
return false;
}
return(true);
}
//+------------------------------------------------------------------+
//| |
//| |
//+------------------------------------------------------------------+
template<typename T>
bool MatrixExtend::XandYSplitMatrices(const matrix<T> &matrix_, matrix<T> &xmatrix, vector<T> &y_vector,int y_column=-1)
{
y_column = int( y_column==-1 ? matrix_.Cols()-1 : y_column);
if (matrix_.Rows() == 0 || matrix_.Cols()==0)
{
#ifdef DEBUG_MODE
printf("%s Line %d Cannot split the matrix of size[%dx%d]",__FUNCTION__,__LINE__,matrix_.Rows(),matrix_.Cols());
#endif
return false;
}
y_vector = matrix_.Col(y_column);
xmatrix.Copy(matrix_);
return RemoveCol(xmatrix, y_column); //Remove the y column
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
void MatrixExtend::Randomize(vector<T> &v, int random_state=-1, bool replace=false)
{
MathSrand(random_state!=-1?random_state:GetTickCount());
int swap_index;
double temp;
int SIZE = (int)v.Size();
vector<T> temp_v = v;
for (int i=0; i<SIZE; i++) //Fisher yates algorithm
{
if (!replace)
{
swap_index = rand() % SIZE;
temp = v[i];
v[i] = v[swap_index];
v[swap_index] = temp;
}
else
{
v[i] = temp_v[MathRandom(0, SIZE)];
}
}
}
//+------------------------------------------------------------------+
//| replace =true parameter allows the same index to be chosen more |
//| than once, simulating the bootstrapping process. |
//+------------------------------------------------------------------+
template<typename T>
void MatrixExtend::Randomize(matrix<T> &matrix_,int random_state=-1, bool replace=false)
{
MathSrand(random_state!=-1?random_state:GetTickCount());
int ROWS=(int)matrix_.Rows(), COL=(int)matrix_.Cols();
int swap_index;
vector<T> temp(COL);
matrix<T> temp_m = matrix_;
int random = 0;
for (int i=0; i<ROWS; i++)
{
if (!replace)
{
swap_index = MathRand() % ROWS;
temp = matrix_.Row(i);
matrix_.Row(matrix_.Row(swap_index),i);
matrix_.Row(temp,swap_index);
}
else
{
random = MathRandom(1, ROWS);
temp = temp_m.Row(random-1);
matrix_.Row(temp, i);
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template <typename T>
void MatrixExtend::TrainTestSplitMatrices(const matrix<T> &X, const vector<T> &y, matrix<T> &x_train, vector<T> &y_train, matrix<T> &x_test, vector<T> &y_test, double train_size=0.7,int random_state=-1, bool shuffle=true)
{
ulong total = X.Rows(), cols = X.Cols();
ulong last_col = cols-1;
//--- Random pseudo matrix
matrix temp_x = X; vector temp_y = y;
if (shuffle)
{
matrix temp_matrix = concatenate(X, y);
Randomize(temp_matrix, random_state);
XandYSplitMatrices(temp_matrix, temp_x, temp_y);
}
//--- Resizing the new metrices
int train = (int)MathFloor(total*train_size);
int test = (int)total-train;
//---
x_train = Slice(temp_x, 0, train);
x_test = Slice(temp_x, train, -1);
//---
y_train = Slice(temp_y, 0, train);
y_test = Slice(temp_y, train, -1);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
matrix MatrixExtend::DesignMatrix(matrix &x_matrix)
{
matrix out_matrix(x_matrix.Rows(),x_matrix.Cols()+1);
vector ones(x_matrix.Rows());
ones.Fill(1);
out_matrix.Col(ones,0);
vector new_vector;
for(ulong i=1; i<out_matrix.Cols(); i++)
{
new_vector = x_matrix.Col(i-1);
out_matrix.Col(new_vector,i);
}
return (out_matrix);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
matrix MatrixExtend::OneHotEncoding(const vector &v)
{
matrix mat = {};
//---
vector v_classes = Unique(v);
//---
mat.Resize(v.Size(),v_classes.Size());
mat.Fill(-100);
for (ulong i=0; i<mat.Rows(); i++)
for (ulong j=0; j<mat.Cols(); j++)
{
if (v[i] == v_classes[j])
mat[i][j] = 1;
else
mat[i][j] = 0;
}
return(mat);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void MatrixExtend::Unique(const string &Array[], string &classes_arr[])
{
string temp_arr[];
ArrayResize(classes_arr,1);
ArrayCopy(temp_arr,Array);
classes_arr[0] = Array[0];
for(int i=0, count =1; i<ArraySize(Array); i++) //counting the different neighbors
{
for(int j=0; j<ArraySize(Array); j++)
{
if(Array[i] == temp_arr[j] && temp_arr[j] != "-nan")
{
bool count_ready = false;
for(int n=0; n<ArraySize(classes_arr); n++)
if(Array[i] == classes_arr[n])
count_ready = true;
if(!count_ready)
{
count++;
ArrayResize(classes_arr,count);
classes_arr[count-1] = Array[i];
temp_arr[j] = "-nan"; //modify so that it can no more be counted
}
else
break;
}
else
continue;
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
vector MatrixExtend::Unique(const vector &v)
{
vector temp_v = v;
vector v_classes={v[0]};
for (ulong i = 0, count=0; i < v.Size(); i++)
{
bool alreadyCounted = false;
for (ulong j = 0; j < v_classes.Size(); j++)
{
if (temp_v[i] == v_classes[j] && temp_v[i] != -DBL_MAX && i!=0)
{
alreadyCounted = true;
temp_v[i] = -DBL_MAX;
}
}
if (!alreadyCounted)
{
count++;
v_classes.Resize(count);
v_classes[count-1] = temp_v[i];
}
}
return MatrixExtend::Sort(v_classes); //Sort the unique values in ascending order
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
T MatrixExtend:: MathRandom(T mini, T maxi)
{
double f = (MathRand() / 32767.0);
return (mini + (T)(f * (maxi - mini)));
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
vector MatrixExtend::Random(T min, T max,int size,int random_state=-1)
{
MathSrand(random_state!=-1?random_state:GetTickCount());
vector v(size);
for (ulong i=0; i<v.Size(); i++)
v[i] = MathRandom<T>(min,max);
return (v);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
matrix MatrixExtend::Random(double min,double max,ulong rows,ulong cols,int random_state=-1)
{
MathSrand(random_state!=-1?random_state:GetTickCount());
matrix mat(rows,cols);
for (ulong r=0; r<rows; r++)
for (ulong c=0; c<cols; c++)
mat[r][c] = MathRandom<double>(min,max);
return (mat);
}
//+------------------------------------------------------------------+
//| Appends vector v1 to the end of vector v2 |
//+------------------------------------------------------------------+
vector MatrixExtend::concatenate(const vector &v1, const vector &v2)
{
vector v_out = v1;
v_out.Resize(v1.Size()+v2.Size());
for (ulong i=0; i<v1.Size(); i++)
v_out[i] = v1[i];
for (ulong i=v1.Size(),index =0; i<v_out.Size(); i++, index++)
v_out[i] = v2[index];
return (v_out);
}
//+------------------------------------------------------------------+
//| Appends matrix mat1 to the end of mat2 |
//+------------------------------------------------------------------+
matrix MatrixExtend::concatenate(const matrix &mat1, const matrix &mat2, int axis = 0)
{
matrix m_out = {};
if ((axis == 0 && mat1.Cols() != mat2.Cols() && mat1.Cols()>0) || (axis == 1 && mat1.Rows() != mat2.Rows() && mat1.Rows()>0))
{
Print(__FUNCTION__, "Err | Dimensions mismatch for concatenation");
return m_out;
}
if (axis == 0) {
m_out.Resize(mat1.Rows() + mat2.Rows(), MathMax(mat1.Cols(), mat2.Cols()));
for (ulong row = 0; row < mat1.Rows(); row++) {
for (ulong col = 0; col < m_out.Cols(); col++) {
m_out[row][col] = mat1[row][col];
}
}