-
Notifications
You must be signed in to change notification settings - Fork 1
/
NeuralNet.py
95 lines (71 loc) · 3.2 KB
/
NeuralNet.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
"""A class to create a basic neural net in Python
Author: Zander Blasingame
Institution: Clarkson University
Lab: CAMEL
"""
import tensorflow as tf
from functools import reduce
class NeuralNet:
"""A basic neural net implementation
Args:
sizes (list of int): List describing the size of each layer
activations (list of function): List of TensorFlow activation functions
must be one less element than the number of elements in
the parameter sizes
Attributes:
network (list of dict): List of dictionaries outlining the weights,
biases, and activation functions at each layer
"""
def __init__(self, sizes, activations):
"""Initializes NeuralNet class"""
assert len(sizes) == len(activations) + 1, (
'sizes and activations have a missmatched number of elements'
)
def create_weights(shape, name):
return tf.Variable(tf.random_normal(shape, stddev=0.1), name=name)
self.network = [{'weights': create_weights([sizes[i], sizes[i+1]],
'w' + str(i)),
'biases': create_weights([sizes[i+1]], 'b' + str(i)),
'activation': activations[i]}
for i in range(len(sizes) - 1)]
def create_network(self, X, keep_prob):
"""Method to construct the network
Args:
X (tf.Tensor): Placeholder Tensor with dimenions of the
training Tensor
keep_prob (tf.Tensor): Placeholder Tensor of rank one
of the probability for the dropout technique
Returns:
(tf.Tensor): A tensor to be evaulated containing the predicted
output of the neural net
"""
def compose_func(a, x, w, b):
return a(tf.matmul(x, w) + b)
prev_value = X
for i, entry in enumerate(self.network):
prev_value = compose_func(entry['activation'],
prev_value,
entry['weights'],
entry['biases'])
if i != len(self.network) - 1:
prev_value = tf.nn.dropout(prev_value, keep_prob)
return prev_value
def reset_weights(self):
"""Resets TensorFlow weights so the model can be used again
Returns:
(list of tf.Operation) List of operations to reassign weights,
run using Session.run()
"""
weights = [entry['weights'] for entry in self.network]
weights.extend([entry['biases'] for entry in self.network])
return [weight.assign(tf.random_normal(weight.get_shape(), stddev=0.1))
for weight in weights]
def get_l2_loss(self):
"""Method to return the L2 loss for L2 regularization techniques
Returns:
(tf.Tensor): A tensor to be evaulated containing the
L2 loss of the network
"""
weights = [entry['weights'] for entry in self.network]
weights.extend([entry['biases'] for entry in self.network])
return reduce(lambda a, b: a + tf.nn.l2_loss(b), weights, 0)