-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMachine_Learning.py
More file actions
1622 lines (1444 loc) · 90.3 KB
/
Machine_Learning.py
File metadata and controls
1622 lines (1444 loc) · 90.3 KB
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
# -----------------------------------------------------------------------------
# Name: Machine Learning
# Purpose: Functions and a class for loading, formatting and interpolating data, as well as generating data,
# training classifiers off of data, and performing tests.
# Author: John Bass
# Created: 7/31/2017
# -----------------------------------------------------------------------------
""" Machine_Learning is a module containing a class and functions for loading,
formatting, and interpolating data, as well as generating fake data to be used,
training classifiers off of data, and performing tests on data.
Requirements
------------
+ [copy](https://docs.python.org/2/library/copy.html)
+ [random](https://docs.python.org/2/library/random.html)
+ [collections](https://docs.python.org/2/library/collections.html)
+ [numpy](https://docs.scipy.org/doc/)
+ [scipy](https://docs.scipy.org/doc/)
+ [pandas](http://pandas.pydata.org/pandas-docs/stable/)
+ [statsmodels](http://www.statsmodels.org/stable/index.html)
+ [matplotlib](https://matplotlib.org/)
+ [scikit-learn](http://scikit-learn.org/stable/)
Examples
---------------
+ [Module Introduction](HTML_Examples/Module_Introduction.html)
+ [Fake Data Generation](HTML_Examples/Fake_Data_Creation.html)
+ [Classifier Comparison](HTML_Examples/Classifier_Comparisons.html)
"""
# Standard Modules:
import copy
from collections import Iterable
import random
# Non-Standard Modules:
try:
import numpy as np
except:
print("The module numpy either was not found or had an error"
"Please put it on the python path, or resolve the error")
raise
try:
import pandas as pd
except:
print("The module numpy either was not found or had an error"
"Please put it on the python path, or resolve the error")
raise
try:
from scipy import interpolate
except:
print("The module scipy.interpolate either was not found or had an error"
"Please put it on the python path, or resolve the error")
raise
try:
from statsmodels.nonparametric.smoothers_lowess import lowess
except:
print("The module statsmodels.nonparametric.smoothers_lowess.lowess either was not found or had an error"
"Please put it on the python path, or resolve the error")
raise
try:
from sklearn.utils import shuffle
except:
print("The module sklearn.utils.shuffle either was not found or had an error"
"Please put it on the python path, or resolve the error")
raise
try:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
except:
print("The module matplotlib was not found."
"Please put it on the python path.")
raise
class DictionarySystem(object):
"""DictionarySystem is a class that contains a nested dictionary that has data that has been split by
unique values of one or more variables. It is used to format and interpolate data,
as well as generate entirely new data."""
# Functions:
def __init__(self, basedict):
"""
To initialize a DictionarySystem,
a nested dictionary must be inputted with the same format that a DictionarySystem uses.
An easy way to create a DictionarySystem is to use any of the following 4 functions:
* split_table_by_column
* split_table_by_columns
* split_csv_by_column
* split_csv_by_columns
"""
# Raises an error if basedict is not a dictionary.
if not isinstance(basedict, dict):
raise ValueError("basedict must be a dictionary!")
elif isinstance(basedict, dict):
# Checks the validity of basedict. If basedict does not have the correct format,
# or has value types that are not DictionarySystems, dictionaries,
# or pandas Dataframes, raises a ValueError.
if self.__check_dictionary_validity(basedict):
self.dictionary = basedict
# Converts all sub-dictionaries into DictionarySystems to
# allow all of the recursive methods to work.
self.__convert_dicts_to_systems()
else:
raise ValueError("Basedict is not in a valid format, or has invalid value types!")
# This is just in case something goes dreadfully wrong, but hopefully it will never be called.
else:
raise ValueError("Alright, I don't know what you even did, but something is wrong with basedict.")
def __getitem__(self, key):
return self.dictionary[key]
def __setitem__(self, key, value):
# This is made to only accept DictionarySystems, dictionaries, and pandas DataFrames,
# or else it will throw an error. I am sure you can figure this method out.
if isinstance(value, (DictionarySystem, pd.DataFrame)):
self.dictionary[key] = value
elif isinstance(value, dict):
self.dictionary[key] = DictionarySystem(value)
else:
raise ValueError("Value set is not a dictionary or pandas dataFrame!")
def __len__(self):
return len(self.dictionary)
def __str__(self):
return "DictionarySystem("+str(self.dictionary)+")"
def __deepcopy__(self):
return DictionarySystem(copy.deepcopy(self.dictionary))
def __delitem__(self, key):
del self.dictionary[key]
# Old Dictionary Methods:
def keys(self):
"""This returns the keys of the DictionarySystem's dictionary."""
return self.dictionary.keys()
def get(self, key, default=None):
"""
Returns a value for a given key inside the DictionarySystem's dictionary.
**key:** the key to be searched in the dictionary.
**default:** The value to be returned in case the key specified does not exist.
**returns:** the value for the given key in side the FDictionarySystem's dictionary.
"""
return self.dictionary.get(key, default)
def pop(self, key, default=None):
"""
Pops the value at the given key from the DictionarySystem's dictionary and returns it.
**key:** The key to pop the value from
**default:** If the given key does not exist within the DictionarySystem's dictionary,
this value will be returned.
**returns:** The value that was just popped from the given key.
"""
return self.dictionary.pop(self, key, default=default)
def items(self):
"""This returns the key,value pairs of the DictionarySystem's dictionary in tuples."""
return self.dictionary.items()
def values(self):
"""This returns a list of all the values in the DictionarySystem's dictionary."""
return self.dictionary.values()
def iteritems(self):
"""Returns the iterator returned by the iteritems method of the DictionarySystem's dictionary."""
return self.dictionary.iteritems()
def iterkeys(self):
"""Returns the iterator returned by the iterkeys method of the DictionarySystem's dictionary."""
return self.dictionary.iterkeys()
def itervalues(self):
"""Returns the iterator returned by the itervalues method of the DictionarySystem's dictionary."""
return self.dictionary.itervalues()
# Table Methods:
def split_by_column(self, column):
"""
Splits the dictionary system's tables by a single column,
making the location where the table was a dictionary containing unique column values in the column as keys,
with each key containing a table.
**column:** The column to split the dictionary systems by.
"""
for key in self.keys():
# If the value at that key is a DictionarySystem it calls split_by_column on that.
if isinstance(self[key], DictionarySystem):
self[key].split_by_column(column)
# If the value at that key is a pandas DataFrame it tries to split it:
elif isinstance(self[key], pd.DataFrame):
# If the column specified is not in the DataFrame, the method raises a KeyError.
if column in self[key] is False:
raise KeyError("Column Specified is not in a table!")
unique_vals = self[key][column].unique()
new_dict = {}
# The method goes through all of the unique values in the column in the table,
# creates new DataFrames containing only the unique value specified, and adds them to a dictionary.
for val in unique_vals:
df = self[key][self[key][column] == val]
df = df.reset_index(drop=True)
new_dict[val] = df
# The dictionary is then set to be the new value of the key.
self[key] = DictionarySystem(new_dict)
# The method will raise an error if the DictionarySystem contains
# values other than DictionarySystems and pandas DataFrames.
else:
raise ValueError("DictionarySystem contains values other than DictionarySystems and tables!")
def split_by_columns(self, *columns):
"""
Does the same thing as the split_by_column method, except splits by multiple columns in order instead of one.
**columns:** The names of each column to split the tables by.
"""
# If no columns are specified, the method raises a ValueError
if len(columns) == 0:
raise ValueError("At least one column value must be specified!")
# Since we now know that columns has some values in it, the method flattens the list of columns.
# I added this so users can input complex nested list systems and stuff as arguments for this method.
columns_flattened = list(self.__better_flatten(columns))
# Now, the method goes through the columns_flattened list and checks if each one of them is a string.
# If one of them is not a string, it clearly isn't a column name, so the methos raises a ValueError.
for val in columns_flattened:
if not isinstance(val, basestring):
raise ValueError("Value other than Iterable or String specified as a column!")
# Jeez, I just realized that like 90% of this entire method is error checking.
# Anyway, this now checks if the length of columns_flattened is 0, and if it is, throws an error.
# I added this because otherwise people could put in a lot of lists and no string column names
# and the method would be okay with it.
if len(columns_flattened) == 0:
raise ValueError("At least one column value must be specified!")
# finally, after all that error checking, the method goes through the columns_flattened list in order, and
# calls split_by_column with each column.
for column in columns_flattened:
self.split_by_column(column)
def remove_column_duplicates(self, column):
"""
Removes all rows that have a duplicate value in a specific column
except one in every table in the DictionarySystem,
so that no duplicates in the said column will remain in the DictionarySystem.
The way this removes columns is by going through each DataFrame in the DictionarySystem, and,
for each DataFrame, a new DataFrame is created containing the first rows containing unique values in the initial
DataFrame. The old DataFrame is then overwritten.
**column:** The column used to remove duplicate values.
"""
for key in self.keys():
# If the value at the current key is a DictionarySystem, it calls remove_column_duplicates on that.
if isinstance(self[key], DictionarySystem):
self[key].remove_column_duplicates(column)
# otherwise, if the value at the current key is a pandas DataFrame, it starts removing column duplicates.
elif isinstance(self[key], pd.DataFrame):
# It sets the variable new_dataframe to none since I didn't want the variable to be local to
# the for loop and I couldn't figure out any other way to do that.
new_dataframe = None
# The method goes through all the unique values of the column specified.
unique_vals = self[key][column].unique()
for val in unique_vals:
# Inside the for loop, the method creates a new DataFrame containing all the rows where the value
# in the specified column is the same as the for loop's unique value. It then selects the first
# row in that DataFrame and adds it to the new_dataframe variable. The result at the end of the
# for loop is a new dataframe where duplicate values in the specified column have been removed.
df = self[key][self[key][column] == val]
if new_dataframe is None:
new_dataframe = df.iloc[[0]]
else:
new_dataframe = pd.concat([new_dataframe, df.iloc[[0]]])
# Finally the method just resets the index of this new DataFrame and sets the value at the current key
# to be the new DataFrame with duplicate values removed, replacing the old DataFrame.
self[key] = new_dataframe.reset_index(drop=True)
# The method will raise an error if the DictionarySystem contains
# values other than DictionarySystems and pandas DataFrames.
else:
raise ValueError("DictionarySystem has a value that isn't a DictionarySystem or Pandas DataFrame!")
def remove_short_tables(self, row_count):
"""
Removes all tables in the DictionarySystem that are below a certain row count.
**row_count:** The row count required for a table to stay in the DictionarySystem.
"""
for key in self.keys():
# If the value at the current key is a DictionarySystem, it calls remove_short_tables on that.
# If the DictionarySystem has no tables left in it after that, the method deletes the current key.
if isinstance(self[key], DictionarySystem):
self[key].remove_short_tables(row_count)
if self[key] is None or len(self[key]) <= 0:
del self[key]
# If the value at the current key is a pandas DataFrame and it's row count is
# less than the specified minimum row count, the method deletes the current key.
elif isinstance(self[key], pd.DataFrame):
if self[key].shape[0] < row_count:
del self[key]
# If the value at the current key is not a DictionarySystem or pandas DataFrame,
# the method raises a ValueError.
else:
raise ValueError("DictionarySystem has a value that isn't a DictionarySystem or Pandas DataFrame!")
def keep_only_certain_columns(self, *columns):
"""
Removes all columns in every table except the ones specified.
This is generally used to remove irrelevant data from tables.
**columns:** The names of the columns to keep in every table.
"""
# If no columns are specified, the method raises a ValueError
if len(columns) == 0:
raise ValueError("At least one column value must be specified!")
# Since we now know that columns has some values in it, the method flattens the list of columns.
# I added this so users can input complex nested list systems and stuff as arguments for this method.
columns_flattened = list(self.__better_flatten(columns))
# Now, the method goes through the columns_flattened list and checks if each one of them is a string.
# If one of them is not a string, it clearly isn't a column name, so the methos raises a ValueError.
for val in columns_flattened:
if not isinstance(val, basestring):
raise ValueError("Value other than Iterable or String specified as a column!")
# The method now checks if the length of columns_flattened is 0, and if it is, throws an error.
# I added this because otherwise people could put in a lot of lists and no string column names
# and the method would be okay with it.
if len(columns_flattened) == 0:
raise ValueError("At least one column value must be specified!")
# Now, most of the error checking is done, so the method starts
# going through the keys in the DictionarySystem.
for key in self.keys():
# If the value at the current key is a DictionarySystem,
# the keep_only_certain_columns method is called on that.
if isinstance(self[key], DictionarySystem):
self[key].keep_only_certain_columns(columns_flattened)
# If the value a the current key is a DataFrame, the method sets the value at the current key to a new
# DataFrame that only has the columns specified.
elif isinstance(self[key], pd.DataFrame):
self[key] = self[key][columns_flattened]
# If the value at the current key is not a DictionarySystem or pandas DataFrame,
# the method will raise an error.
else:
raise ValueError(
"DictionarySystem has a value that isn't a DictionarySystem or Pandas DataFrame!")
# Array Methods:
def interpolate_data(self,
num_points,
independent_variable,
dependent_variables,
interpolation_kind="cubic"):
"""
Interpolates independent and dependent variables in datasets within the DictionarySystem to have the amount
of points specified. Unfortunately, columns that are not the independent or dependent variables will be removed,
since they are not being interpolated and the dataframe has to stay rectangular.
The independent variable must not have repeat values, and must be increasing. If these two requirements are not
fulfilled, the method will fail.
**num_points:** The amount of points the dependent variables will be interpolated to.
**independent_variable:** The name of the independent variable of the dataset.
All values of this variable must be increasing, and no duplicate values can exist.
**dependent_variables:** An iterable containing the names of the dependent variables of the dataset.
**interpolation_kind:** The kind of interpolation to be used. This will be fed into scipy's interp1d method.
"""
# Gets all of the nested dictionaries within the DictionarySystem.
# This basically just gets the entire nested dictionary structure without any DictionarySystems in it.
nested_dictionaries = self.__get_nested_dictionaries()
# This converts all dataframes at the end of the nested dictionary structure to dictionaries
# containing arrays representing columns.
self.__nested_dictionary_dataframes_to_arrays(nested_dictionaries)
# Now that our data is in a format that is easy to work with, we actually interpolate our data.
self.__nested_array_dictionary_interpolation(nested_dictionaries,
num_points,
independent_variable,
dependent_variables,
interpolation_kind=interpolation_kind)
# Now that our data is interpolated, we convert all of the dictionaries containing
# arrays representing columns back to dataframes.
self.__nested_dictionary_arrays_to_dataframes(nested_dictionaries)
# We replace our object's dictionary with the newly interpolated one.
self.dictionary = nested_dictionaries
# Now we simply convert all sub-dictionaries to DictionarySystems
# to get everything back into the correct format.
self.__convert_dicts_to_systems()
def make_fake_data_system_noise(self,
independent_var,
dependent_vars,
num_datasets,
location,
randomness_amplitudes):
"""
Creates a new DictionarySystem containing automatically generated datasets created by adding random noise to
the dependent variables of real datasets.
**independent_var:** The name of the independent variable of the datasets.
This will not have random noise added to it.
**dependent_vars:** An Iterable containing the names of the dependent variables of the datasets.
These will have random noise added to their values to generate new datasets.
**num_datasets:** The amount of datasets to create
**location:** The location to generate fake data at.
**randomness_amplitudes** An iterable containing the random noise amplitudes for the random noise to be
added to the values for each dependent variable.
**returns:** A new DictionarySystem containing automatically generated datasets.
"""
# Gets all of the nested dictionaries within the DictionarySystem.
# This basically just gets the entire nested dictionary structure without any DictionarySystems in it.
nested_dictionaries = self.__get_nested_dictionaries()
# This converts all dataframes at the end of the nested dictionary structure to dictionaries
# containing arrays representing columns.
self.__nested_dictionary_dataframes_to_arrays(nested_dictionaries)
# Now that our data is in a format that is somewhat easy to work with, we actually create the fake data.
# I had to use a seperate method here since my method of creating fake data used recursion.
new_dictionaries = self.__nested_array_fake_noise_data_creation(nested_dictionaries,
independent_var,
dependent_vars,
num_datasets,
location,
randomness_amplitudes)
# Now that we have our fake data, we convert all the dictonaries of arrays representing columns to dataframes.
self.__nested_dictionary_arrays_to_dataframes(new_dictionaries)
# Finally we convert this dictionary into a DictionarySystem and return it.
return DictionarySystem(new_dictionaries)
def make_fake_data_system_slope(self,
independent_var,
dependent_vars,
num_datasets,
location,
starting_noises,
slope_deviations,
smoothing_fracs):
"""
Creates a new DictionarySystem containing automatically generated datasets created by adding random noise to the
first points of already existing datasets then adding random noise to the slopes between points of existing
datasets and creating new points based off of those. After all this is done, a smoothing filter is applied to
make the generated lines less jagged.
**independent_var:** The name of the independent variable of the datasets.
This will not be modified during fake data creation.
**dependent_vars:** An Iterable containing the names of the dependent variables of the datasets.
Values of these variables in existing datasets will have modifications applied to them to generate new datasets.
**num_datasets:** The amount of datasets to be generated.
**location:** The location to get datasets to be used to generate new datasets.
**starting_noises:** An Iterable containing the random noise amplitudes for the random noise to be added to
each dependent variable in existing datasets to generate new datasets.
**slope_deviations:** An Iterable containing the random noise amplitudes for the random noise to be added to
the slopes of the lines for each dependent variable to generate new datasets.
**smoothing_fracs:** An Iterable containing the smoothing fracs for the lowess filter to apply to the
generated lines for each dependent variable.
**returns:** A new DictionarySystem containing automatically generated datasets.
"""
# Gets all of the nested dictionaries within the DictionarySystem.
# This basically just gets the entire nested dictionary structure without any DictionarySystems in it.
nested_dictionaries = self.__get_nested_dictionaries()
# This converts all dataframes at the end of the nested dictionary structure to dictionaries
# containing arrays representing columns.
self.__nested_dictionary_dataframes_to_arrays(nested_dictionaries)
# Now that our data is in a format that is somewhat easy to work with, we actually create the fake data.
# I had to use a seperate method here since my method of creating fake data used recursion.
new_dictionaries = self.__nested_array_fake_slope_data_creation(nested_dictionaries,
independent_var,
dependent_vars,
num_datasets,
location,
starting_noises,
slope_deviations,
smoothing_fracs)
# Now that we have our fake data, we convert all the dictonaries of arrays representing columns to dataframes.
self.__nested_dictionary_arrays_to_dataframes(new_dictionaries)
# Finally we convert this dictionary into a DictionarySystem and return it.
return DictionarySystem(new_dictionaries)
def get_dataset_variable_values(self, dataset_variable, location=None):
"""
This gets all of the values for a single variable, and returns them in an array containing lists containing the
datapoints for the variable for a single dataset. This is used by a lot of methods, and in general is a format
that is somewhat easy to work with.
**dataset_variable:** The name of the variable to get all of the values for.
**location:** The location to get the variable values from. If it is none, all of the values for the variable
will be gotten.
**returns:** All of the values of a single variable in an array, with the values being seperated into lists
containing the values for a single dataset.
"""
nested_dictionaries = self.__get_nested_dictionaries()
self.__nested_dictionary_dataframes_to_arrays(nested_dictionaries)
dataset_variable_values = self.__nested_dictionary_get_dataset_variable_values(nested_dictionaries,
dataset_variable,
location)
return dataset_variable_values
# Array Helper Methods:
def __nested_dictionary_get_dataset_variable_values(self,
dictionary,
dataset_variable,
location=None):
"""
Helper method used by the get_dataset_variable_values method that actually gets the values of the variables for
each dataset and outputs them in the right format. This method uses recursion so it had to be seperate from the
other method.
**dictionary:** The dictionary to get the values of the variables for each dataset from.
**dataset_variable:** The name of the variable to get values from.
**location:** The location to get the data from. If location is none, it will get dataset variable values
from the entire dictionary.
**returns** An array containing lists containing the values for a specific variable in each dataset,
at the specified location.
"""
# If no location was inputted, it simply gets all of the dataset
# variable values in every dataset and returns an array of those.
if location is None:
# This list will contain the list of values of the dataset variable for every dataset in
# the DictionarySystem.
variable_set_list = []
for key in dictionary.keys():
# If the value at the first key in the current dictionary is an array,
# it adds the array whose key is the dataset variable name to variable_set_list
if isinstance(dictionary[key].values()[0], np.ndarray):
variable_set_list.append(dictionary[key][dataset_variable].tolist())
# if the current location is an DictionarySystem that contains DictionarySystems representing
# individual datasets, it goes through them calls get_dataset_variable_values to each one,
# then adds them all to variable_set_list.
elif isinstance(dictionary[key].values()[0].values()[0], np.ndarray):
key_results = self.__nested_dictionary_get_dataset_variable_values(dictionary[key],
dataset_variable,
location=[]).tolist()
if isinstance(key_results[0], list):
variable_set_list.extend(key_results)
else:
variable_set_list.append(key_results)
# if the current location is higher up in the nesting, the method calls get_dataset_variable_values on
# the DictionarySystem at the current location and adds the results to variable_set_list.
else:
key_results = self.__nested_dictionary_get_dataset_variable_values(dictionary[key],
dataset_variable,
location=None).tolist()
if isinstance(key_results[0], list):
variable_set_list.extend(key_results)
else:
variable_set_list.append(key_results)
# Finally, variable_set_list is returned as an array.
return np.array(variable_set_list)
# Since location can also be a string, if it is, it checks to see if location is an empty string.
# If location is an empty string, it calls get_dataset_variable_values with location being an empty tuple.
# If location is not an empty string, it calls get_dataset_variable_values with location being a
# single value tuple with the only value being the string that was just passed to location.
elif isinstance(location, basestring):
if len(location) == 0:
return self.__nested_dictionary_get_dataset_variable_values(dictionary,
dataset_variable,
location=[]).tolist()
return self.__nested_dictionary_get_dataset_variable_values(dictionary,
dataset_variable,
location=[location]).tolist()
# If location is an iterable, but not a string, then that means we are looking at some sort of path.
elif isinstance(location, Iterable) and not isinstance(location, basestring):
# If the length of location is 0, then that means that the current location is the location to
# get the dataset variable's values from, so we go through the DictionarySystem at the current location
# and add all of the values of the dataset variable to a list, then return it as an array.
if len(location) == 0:
variable_set_list = []
for key in dictionary.keys():
variable_set_list.append(dictionary[key][dataset_variable].tolist())
return np.array(variable_set_list)
# If the length of location is 1 then we can do the same thing as when location is 0 with a bit of tweaking.
elif len(location) == 1:
current_location = location[0]
variable_set_list = []
for key in dictionary[current_location].keys():
variable_set_list.append(dictionary[current_location][key][dataset_variable].tolist())
return np.array(variable_set_list)
# If the length of location is greater than one then we just use recursion to our advantage.
else:
return self.__nested_dictionary_get_dataset_variable_values(dictionary[location[0]],
dataset_variable,
location=location[1:]).tolist()
# If location is not None, a string, or an Iterable, we raise a ValueError.
else:
raise ValueError("location must be an Iterable!")
def __nested_array_fake_slope_data_creation(self,
dictionary,
independent_var,
dependent_vars,
num_datasets,
location,
starting_noises,
slope_deviations,
smoothing_fracs):
"""
The method used by the make_fake_data_system_slope method to generate fake data. This method is seperate from
that method because this method requires the use of recursion.
**dictionary:** The dictionary that will be used as a reference for the fake data generation.
**independent_var:** The name of the independent variable of the datasets.
This will not be modified during fake data creation.
**dependent_vars:** An Iterable containing the names of the dependent variables of the datasets.
Values of these variables in existing datasets will have modifications applied to them to generate new datasets.
**num_datasets:** The amount of datasets to be generated.
**location:** The location to get datasets to be used to generate new datasets.
**starting_noises:** An Iterable containing the random noise amplitudes for the random noise to be added to
each dependent variable in existing datasets to generate new datasets.
**slope_deviations:** An Iterable containing the random noise amplitudes for the random noise to be added to
the slopes of the lines for each dependent variable to generate new datasets.
**smoothing_fracs:** An Iterable containing the smoothing fracs for the lowess filter to apply to the
generated lines for each dependent variable.
**returns:** A nested dictionary containing the newly generated data.
"""
if isinstance(location, Iterable) and len(location) > 0 and not isinstance(location, basestring):
if len(location) == 1:
current_location = location[0]
new_data_dict = {}
for fake_set_num in range(num_datasets):
# Copying a random dataset in our already existing datasets,
# which will be modified to become fake data.
new_set_values = copy.deepcopy(dictionary[current_location]
[random.choice(dictionary[current_location].keys())])
# This will go through each dependent variable's datapoints and modify them.
for dep_var_index in range(len(dependent_vars)):
# This is the array of the old points from an existing dataset.
dep_var_values = new_set_values[dependent_vars[dep_var_index]]
new_dep_var_points = []
# This adds a random value to the starting value of dep_var_values,
# creating the first point in our fake dataset.
starting_value = dep_var_values[0] + np.random.normal(0, starting_noises[dep_var_index])
new_dep_var_points.append(starting_value)
for set_index in range(len(dep_var_values)-1):
# We need to modify the slope, so we first have to get the slope.
# To do this, we first have to get the change in the x value:
delta_x = new_set_values[independent_var][set_index+1] -\
new_set_values[independent_var][set_index]
# We also need to get the change in the y value:
delta_y = dep_var_values[set_index+1]-dep_var_values[set_index]
# Now we simply calculate the slope:
segment_slope = delta_y / delta_x
# We then add a random value to the slope,
# and use our new slope to calculate the next point.
segment_slope += np.random.normal(0, slope_deviations[dep_var_index])
new_point_y_val = new_dep_var_points[set_index] + (delta_x * segment_slope)
new_dep_var_points.append(new_point_y_val)
# Now that we have all of our points, we apply a smoothing filter to our points so that
# our curve will not have as many sharp edges.
smoothed_dep_var_points = lowess(new_dep_var_points,
new_set_values[independent_var],
is_sorted=True,
frac=smoothing_fracs[dep_var_index],
it=0)[:,1]
new_set_values[dependent_vars[dep_var_index]] = smoothed_dep_var_points
new_data_dict["Fake Dataset " + str(fake_set_num)] = new_set_values
return new_data_dict
else:
# if the length of location is more than one, we simply use recursion to narrow down the location:
return self.__nested_array_fake_slope_data_creation(dictionary[location[0]],
independent_var,
dependent_vars,
num_datasets,
location[1:],
starting_noises,
slope_deviations,
smoothing_fracs)
elif isinstance(location, basestring):
return self.__nested_array_fake_slope_data_creation(dictionary,
independent_var,
dependent_vars,
num_datasets,
[location],
starting_noises,
slope_deviations,
smoothing_fracs)
else:
raise ValueError("Location must be an iterable or a string!")
def __nested_array_fake_noise_data_creation(self,
dictionary,
independent_var,
dependent_vars,
num_datasets,
location,
randomness_amplitudes):
"""
The method used by the make_fake_data_system_noise method to generate fake data. This method is seperate from
that method because this method requires the use of recursion.
**dictionary:** The dictionary that will be used as a reference for the fake data generation.
**independent_var:** The name of the independent variable of the datasets.
This will not have random noise added to it.
**dependent_vars:** An Iterable containing the names of the dependent variables of the datasets.
These will have random noise added to their values to generate new datasets.
**num_datasets:** The amount of datasets to create.
**location:** The location to generate fake data at.
**randomness_amplitudes:** An iterable containing the random noise amplitudes for the random noise to be
added to the values for each dependent variable.
**returns:** A nested dictionary containing the newly generated data.
"""
if isinstance(location, Iterable) and len(location) > 0 and not isinstance(location, basestring):
# If it's length is one, that means that means that all of the values in the current dictionary
# are SUPPOSED to be dictionaries representing singular datasets.
if len(location) == 1:
# the current_location variable is just there so I don't have to keep writing location[0] a ton.
current_location = location[0]
# new_data_dict will contain all of the new, fake datasets.
new_data_dict = {}
for i in range(num_datasets):
# We need a deep copy of one of the datasets so that
# when we add random noise it won't affect the original dataset:
new_set_values = copy.deepcopy(dictionary[current_location]
[random.choice(dictionary[current_location].keys())])
# Now we add random noise to every single dependent variable:
for dependent_var, amp in zip(dependent_vars, randomness_amplitudes):
num_values_in_dataset = len(new_set_values[dependent_var])
new_set_values[dependent_var] += np.random.normal(0, amp, num_values_in_dataset)
# We now have a fake dataset, so we add it to new_data_dict, which contains all of our fake datasets
new_data_dict["Fake Dataset " + str(i)] = new_set_values
# ...and now we just return new_data_dict!
return new_data_dict
else:
# if the length of location is more than one, we simply use recursion to narrow down the location:
return self.__nested_array_fake_noise_data_creation(dictionary[location[0]],
independent_var,
dependent_vars,
num_datasets,
location[1:],
randomness_amplitudes)
# If location is a string, the same method is called, but location is now a single element list,
# so that The above code can do it's magic.
elif isinstance(location, basestring):
return self.__nested_array_fake_noise_data_creation(dictionary,
independent_var,
dependent_vars,
num_datasets,
[location],
randomness_amplitudes)
# If location is not an iterable or a string, a ValueError is raised.
else:
raise ValueError("Location must be an iterable or a string!")
def __nested_dictionary_dataframes_to_arrays(self, dictionary):
"""
This method converts a nested dictionary with dataframes at the end of the nesting to a nested dictionary with
dictionaries containing arrays representing columns at the end of the nesting.
**dictionary:** The dictionary to modify.
"""
# If dictionary is not a dict, an error is raised.
if not isinstance(dictionary, dict):
raise ValueError("parameter 'dictionary' is not a dict, it is a " + str(type(dictionary)))
for key in dictionary.keys():
# If the value at the current key is a dataframe,
# it gets converted into a dictionary containing lists representing columns.
if isinstance(dictionary[key], pd.DataFrame):
dictionary[key] = dictionary[key].to_dict(orient='list')
# All of the lists are now converted to arrays.
for subkey in dictionary[key].keys():
dictionary[key][subkey] = np.array(dictionary[key][subkey])
# If the value at the current key is a dict, it gets the method called on it.
elif isinstance(dictionary[key], dict):
self.__nested_dictionary_dataframes_to_arrays(dictionary[key])
def __nested_dictionary_arrays_to_dataframes(self, dictionary):
"""
This method converts a nested dictionary with dictionaries containing arrays representing columns at the end of
the nesting to a nested dictionary with dataframes at the end of the nesting.
**dictionary: The dictionary to modify.
"""
# If dictionary is not a dict, an error is raised.
if not isinstance(dictionary, dict):
raise ValueError("parameter 'dictionary' is not a dict, it is a " + str(type(dictionary)))
for key in dictionary.keys():
# If the value at the current key is a dictionary containing arrays representing columns,
# It gets converted to a dataframe.
if isinstance(dictionary[key].values()[0], np.ndarray):
dictionary[key] = pd.DataFrame.from_dict(dictionary[key])
# If the value at the current key is a dict, it gets the method called on it.
elif isinstance(dictionary[key].values()[0], dict):
self.__nested_dictionary_arrays_to_dataframes(dictionary[key])
def __nested_array_dictionary_interpolation(self,
dictionary,
num_points,
independent_variable,
dependent_variables,
interpolation_kind="cubic"):
"""
This is the method that actually interpolates the data in a nested dictionary, and is only called by
the interpolate_data method. The reason why this method and the interpolate_data method are separate methods is
because this method requires recursion.
**dictionary:** A nested dictionary which will have its datasets interpolated.
**num_points:** The amount of points the dependent variables will be interpolated to.
**independent_variable:** The name of the independent variable of the dataset.
All values of this variable must be increasing, and no duplicate values can exist.
**dependent_variables:** An iterable containing the names of the dependent variables of the dataset.
**interpolation_kind:** The kind of interpolation to be used. This will be fed into scipy's interp1d method.
"""
for key in dictionary.keys():
if isinstance(dictionary[key].values()[0].values()[0], np.ndarray):
maximum_of_mins = None
minimum_of_maxes = None
for dataset_key in dictionary[key].keys():
if independent_variable not in dictionary[key][dataset_key].keys():
raise KeyError("Independent variable specified is not a key in the DictionarySystem!")
# All of this here is simple code to find these maxes of minimums and minimums of maxes:
if maximum_of_mins is None:
maximum_of_mins = dictionary[key][dataset_key][independent_variable].min()
elif dictionary[key][dataset_key][independent_variable].min() > maximum_of_mins:
maximum_of_mins = dictionary[key][dataset_key][independent_variable].min()
if minimum_of_maxes is None:
minimum_of_maxes = dictionary[key][dataset_key][independent_variable].max()
elif dictionary[key][dataset_key][independent_variable].max() < minimum_of_maxes:
minimum_of_maxes = dictionary[key][dataset_key][independent_variable].max()
# Now that we have the bounds for our interpolation, we need to make our interpolation functions:
for dataset_key in dictionary[key].keys():
# First we need to get the values for the independent and
# dependent variables in this specific dataset:
independent_var_values = dictionary[key][dataset_key][independent_variable].tolist()
dependent_var_values = [
dictionary[key][dataset_key][variable_name].tolist() for variable_name in dependent_variables]
# This list will hold the interpolation functions soon:
dependent_var_interpolation_functions = []
for dependent_var_list in dependent_var_values:
# Now, we simply use scipy's interp1d function to get our interpolation functions:
var_function = interpolate.interp1d(independent_var_values,
dependent_var_list,
interpolation_kind)
dependent_var_interpolation_functions.append(var_function)
# The new independent variable values should be uniform, so we just use np.linspace:
new_independent_var_values = np.linspace(maximum_of_mins, minimum_of_maxes, num_points)
# This list will be used to store our dependent variable values
# once we use the interpolation functions we just made:
new_dependent_var_values = []
try:
# Now we go through our interpolation functions and
# get new values for all of our dependent variables:
for interp_function in dependent_var_interpolation_functions:
new_dependent_var_values.append(interp_function(new_independent_var_values))
# We make a dictionary out of these new values using variable names as keys:
interpolated_dictionary = dict(zip(dependent_variables, new_dependent_var_values))
interpolated_dictionary[independent_variable] = new_independent_var_values
# Finally, we replace our old DictionarySystem for this dataset with
# our newly interpolated one. By the way, we are inputting a dictionary, but the __setitem__
# method will convert it into an DictionarySystem, so we do not have to worry about that.
dictionary[key][dataset_key] = interpolated_dictionary
# Sometimes interpolation fails because some dataset's bounds are outside of the
# interpolation range we just got, so this is here to just remove all the datasets that do that.
except ValueError:
del dictionary[key][dataset_key]
continue
elif isinstance(dictionary[key].values()[0].values()[0], dict):
self.__nested_array_dictionary_interpolation(dictionary[key],
num_points,
independent_variable,
dependent_variables,
interpolation_kind=interpolation_kind)
else:
raise ValueError("Something went wrong, change this error message later")
# Other Helper Methods:
def __get_nested_dictionaries(self):
"""
This gets all of the dictionaries in the nested DictionarySystems
and returns them as a nested dictionary structure.
"""
# This will soon contain all of the nested dictionaries in the DictionarySystem.
nested_dict = {}
# This basically goes through the DictionarySystem, calling the same method on sub-DictionarySystems and
# appending their results to the dictionary, as well as adding any non-DictionarySystem values to the dictionary
for key in self.keys():
if isinstance(self[key], DictionarySystem):
nested_dict[key] = self[key].__get_nested_dictionaries()
else:
nested_dict[key] = self[key]
# Finally, our nested dictionary is just returned. Due to recursion, a full nested dictionary structure will
# Eventually be outputted.
return nested_dict
def __check_dictionary_validity(self, dictionary):
"""
Checks if a dictionary has a valid format and valid variable types to become a DictionarySystem.
**dictionary:** The dictionary to check.
**returns:** True or False depending on whether a dictionary has a valid format and valid variable types.
"""
# If the dictionary variable inputted is not a dictionary, returns False.
if isinstance(dictionary, (DictionarySystem, dict)):
for key in dictionary.keys():
# If any value in the dictionary is not a DictionarySystem, dictionary, or
# pandas DataFrame, returns False.
if isinstance(dictionary[key], (DictionarySystem, dict)):
# If the __check_dictionary_validity method fails on any sub dictionaries, returns False.
if not self.__check_dictionary_validity(dictionary[key]):
return False
elif isinstance(dictionary[key], pd.DataFrame):
continue
else:
return False
else:
return False
# If it never returned False, returns True.
return True
def __convert_dicts_to_systems(self):
"""
Converts all sub-dictionaries in the DictionarySystem's main dictionary into DictionarySystems.
"""
# Literally all this does is if any value in the DictionarySystem is a dictionary, it gets turned into a
# DictionarySystem.
for key in self.keys():
if isinstance(self[key], dict):
self[key] = DictionarySystem(self[key])
def __better_flatten(self, iterable_object):
"""Some flattening method I found on stackoverflow, which I a few methods
to make the flattening of my columns arguments work."""
for value in iterable_object:
if isinstance(value, Iterable) and not isinstance(value, basestring):
for newvalue in self.__better_flatten(value):
yield newvalue
else:
yield value
def split_table_by_column(table, column):
"""
Takes a pandas DataFrame and splits it by column values into a DictionarySystem.
**table:** The Dataframe to split into a DictionarySystem.
**column:** The column to split the pandas DataFrame by.
**returns:** A DictionarySystem created by splitting the pandas DataFrame inputted by the column inputted
"""
table_dictionary = {}
# Goes through every unique value in the specified column of the the table inputted
unique_column_vals = table[column].unique()
for val in unique_column_vals:
# Adds to the dictionary a new table with every value in the
# specified column being the current unique value from the for loop.
table_dictionary[val] = table[table[column] == val]
return DictionarySystem(table_dictionary)
def split_table_by_columns(table, *columns):
"""
Takes a pandas DataFrame and splits it by all of the columns specified into a DictionarySystem
**table:** The Dataframe to split into a DictionarySystem.
**columns:** The columns to split the pandas DataFrame by.
**returns:** A DictionarySystem created by splitting the pandas DataFrame inputted by the columns inputted
"""
# Raises a ValueError if no columns are inputted:
if len(columns) == 0:
raise ValueError("At least one column must be specified!")
# Splits the table by the first column: