-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_import_utils.py
More file actions
174 lines (152 loc) · 5.41 KB
/
data_import_utils.py
File metadata and controls
174 lines (152 loc) · 5.41 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
import csv
import numpy as np
def import_data(filepath, csv_delimiter = ',', skip_first_line = True):
'''
This function reads (filepath) as csv
The assumption is that the last column contains the classes
The return is a pair of lists
X = list of lists of inputs
Y = list of corresponding outputs
'''
with open(filepath, newline='') as f:
reader = csv.reader(f, delimiter=csv_delimiter)
first_line = True
X = []
Y = []
for row in reader:
if skip_first_line and first_line:
first_line = False
#column_labels = row
continue
X.append([float(i) for i in row[:-1]])
Y.append(float(row[-1]))
return X, Y
def import_data_2Y(filepath, csv_delimiter = ',', skip_first_line = True):
'''
This function reads (filepath) as csv
The assumption is that the last column contains the classes
The return is a pair of lists
X = list of lists of inputs
Y = list of lists of corresponding outputs
'''
with open(filepath, newline='') as f:
reader = csv.reader(f, delimiter=csv_delimiter)
first_line = True
X = []
Y = []
for row in reader:
if skip_first_line and first_line:
first_line = False
#column_labels = row
continue
X.append([float(i) for i in row[:-2]])
Y.append([float(i) for i in row[-2:]])
return X, Y
class Scaler():
''' Scale an input matrix for the appropriate activation function for a NN
For logistic sigmoid:
Scale data from 0 to 1
d = (D - m) / (M - m)
where
d = scaled data
D = input data
M = max value in that column
m = min value in that column
For relu:
Scale data from 0 to inf
d = (D - m)
where
d = scaled data
D = input data
m = min value in that column
For standardize:
Scale data to mean=0 and variance=1
d = (D - mu)/sigma
where
d = scaled data
D = input data
mu = mean value of that column
sigma = stdev of that column
Parameters
-------
activation : string {'relu', 'logistic', 'standardize'}
The activation function to scale for
Attributes
--------
n_components_ : int
Number of columns that were fitted
X_max_ : np array
Max of each column
X_min_ : np array
Min of each column
X_mean_ : np array
Mean of each column
X_stdev_ : np array
Standard Deviation of each column
'''
def __init__(self, activation = 'relu'):
self.activation = activation
def fit(self, X):
''' Fit the scaler to X '''
X = np.array(X)
try:
_, self.n_components_ = np.shape(X)
except:
self.n_components_ = 1
self.X_max_ = np.max(X, axis=0)
self.X_min_ = np.min(X, axis=0)
self.X_mean_ = np.mean(X, axis=0)
self.X_stdev_ = np.std(X, axis=0)
def transform(self, X):
''' Transform X
Return X: transformed np matrix'''
X = np.array(X)
try:
m, n = X.shape
except:
(m,) = np.shape(X)
n = 1
if n != self.n_components_:
raise ValueError(f"Input matrix columns ({n}) is not same as fitted matrix columns ({self.n_components})")
if self.activation == 'relu':
X -= self.X_min_
if self.activation == 'logistic' or self.activation == 'sigmoid':
X -= self.X_min_
X /= (self.X_max_ - self.X_min_)
if self.activation == 'standardize':
X -= self.X_mean_
X /= self.X_stdev_
mean_2 = X.mean(axis=0)
# If mean_2 is not 'close to zero', it comes from the fact that
# scale_ is very small so that mean_2 = mean_1/scale_ > 0, even
# if mean_1 was close to zero. The problem is thus essentially
# due to the lack of precision of mean_. A solution is then to
# subtract the mean again:
if not np.allclose(mean_2, 0):
warnings.warn("Numerical issues were encountered "
"when scaling the data "
"and might not be solved. The standard "
"deviation of the data is probably "
"very close to 0. ")
# X -= mean_2
return X
def inv_transform(self, X):
''' inverse transform X
Return X: inversely transformed np matrix'''
X = np.array(X)
try:
m, n = X.shape
except:
(m,) = np.shape(X)
n = 1
if n != self.n_components_:
raise ValueError(f"Input matrix columns ({n}) is not same as fitted matrix columns ({self.n_components})")
if self.activation == 'relu':
X += self.X_min_
if self.activation == 'logistic' or self.activation == 'sigmoid':
X *= (self.X_max_ - self.X_min_)
X += self.X_min_
if self.activation == 'standardize':
X *= self.X_stdev_
X += self.X_mean_
return X