-
Notifications
You must be signed in to change notification settings - Fork 24
/
helpers.py
228 lines (178 loc) · 5.45 KB
/
helpers.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
import numpy as np
import pandas as pd
import random
random.seed(1104)
def generate_x_y(random_seed=1104):
random.seed(random_seed)
randX = random.sample(range(1,9), 8)
mapping_dict = {1:[0,0,0],
2:[0,0,1],
3:[0,1,0],
4:[0,1,1],
5:[1,0,0],
6:[1,0,1],
7:[1,1,0],
8:[1,1,1]}
X = []
for r in randX:
X.append(mapping_dict[r])
y = []
randy = random.sample(range(1,9), 8)
for el in randy:
if el % 2 == 0:
y.append([0])
else:
y.append([1])
X = np.array(X)
y = np.array(y)
df = pd.DataFrame(data=np.concatenate([X, y], axis=1),
columns=['X1', 'X2', 'X3', 'y'])
return df, X, y
def array_print(array, round_num=2):
'''
`array` is 2 dimensional
'''
assert array.ndim == 2
print("The array:\n",
np.round(array, round_num))
text_lookup = {"rows": {"one": "row", "other": "rows"}, "columns": {"one": "column", "other": "columns"}}
if array.shape[0] == 1:
rows_text = text_lookup['rows']['one']
else:
rows_text = text_lookup['rows']['other']
if array.shape[1] == 1:
columns_text = text_lookup['columns']['one']
else:
columns_text = text_lookup['columns']['other']
print("The dimensions are",
array.shape[0],
rows_text,
"and",
array.shape[1],
columns_text)
def df_print(df, round_num=2):
print(np.round(df, 2))
def target_to_y(target):
Y = np.zeros((len(target), 10))
for i in range(len(target)):
Y[i][int(target[i])] = 1
return Y
def data_to_x(data):
X = (data - data.min()) * 1.0 / (data.max() - data.min())
return X
def get_mnist_X_Y(mnist):
data = mnist.data
target = mnist.target
X = data_to_x(data)
Y = target_to_y(target)
return X, Y
###
### Neural net functions
###
def initialize_weights(num_in=3, num_hidden=4, num_out=1):
'''
Randomly initializes weights
'''
np.random.seed(1104)
V = np.random.randn(num_in, num_hidden)
W = np.random.randn(num_hidden, num_out)
return V, W
def shuffle_x_y(X, Y):
'''
Each array must be two dimensional
'''
np.random.seed(1104)
train_size = X.shape[0]
indices = list(range(train_size))
np.random.shuffle(indices)
return X[indices], Y[indices]
def sigmoid(x):
return 1.0/(1.0+np.exp(-x))
def learn(V, W, x_batch, y_batch):
# forward pass
A = np.dot(x_batch,V)
B = sigmoid(A)
C = np.dot(B,W)
P = sigmoid(C)
# loss
L = 0.5 * (y_batch - P) ** 2
# backpropogation
dLdP = -1.0 * (y_batch - P)
dPdC = sigmoid(C) * (1-sigmoid(C))
dLdC = dLdP * dPdC
dCdW = B.T
dLdW = np.dot(dCdW, dLdC)
dCdB = W.T
dBdA = sigmoid(A) * (1-sigmoid(A))
dAdV = x_batch.T
dLdV = np.dot(dAdV, np.dot(dLdP * dPdC, dCdB) * dBdA)
# update the weights
W -= dLdW
V -= dLdV
return V, W
def one_epoch(X, Y, V, W):
'''
Run one epoch an element at a time through the net.
'''
for index in range(X.shape[0]):
x_batch = np.array(X[index], ndmin=2)
y_batch = np.array(Y[index], ndmin=2)
learn(V, W, x_batch, y_batch)
return V, W
def predict(x_batch, V, W):
'''
Make a prediction given a batch of observations and the weights.
'''
A = np.dot(x_batch, V)
B = sigmoid(A)
C = np.dot(B, W)
P = sigmoid(C)
return P
def loss(prediction, actual, print_loss=False):
'''
Calculate the loss as mean squared error.
'''
return np.mean((prediction - actual) ** 2) * actual.shape[1]
def train(X, Y, V, W, epochs=100):
'''
Train the net for a number of epochs.
'''
losses = []
epochs_list = []
for i in range(epochs+1):
V, W = one_epoch(X, Y, V, W)
if i % (epochs / 10) == 0:
preds = predict(X, V, W)
loss_epoch = loss(preds, Y)
epochs_list.append(i)
losses.append(loss_epoch)
return pd.DataFrame({'epoch' : epochs_list,
'loss' : losses})
def train_and_display(X, Y, num_epochs=1000, num_hidden=8):
X, Y = shuffle_x_y(X, Y)
V, W = initialize_weights(num_in=X.shape[1],
num_hidden=num_hidden,
num_out=Y.shape[1])
df = train(X, Y, V, W, num_epochs)
df_print(df)
return V, W
def accuracy_binary(X, Y, V, W):
def _df_actual_predicted(X, Y, V, W):
return pd.DataFrame(np.round(np.concatenate([Y, predict(X, V, W)], axis=1), 2),
columns=["Actual", "Predicted"])
df = _df_actual_predicted(X, Y, V, W)
print("The data frame of the predictions this neural net produces is:\n",
df)
df['Prediction'] = df['Predicted'] > 0.5
def _correct_prediction(row):
return bool(row['Actual']) == row['Prediction']
df['Correct'] = df.apply(lambda x: _correct_prediction(x), axis=1)
print("The accuracy of this trained neural net is",
df['Correct'].sum() / len(df['Correct']))
return df['Correct'].sum() / len(df['Correct'])
def accuracy_multiclass(X, Y, V, W):
predictions = predict(X, V, W)
preds = [np.argmax(x) for x in predictions]
actuals = [np.argmax(x) for x in Y]
accuracy = sum(np.array(preds) == np.array(actuals)) * 1.0 / len(preds)
return accuracy