-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathneural_network.py
183 lines (164 loc) · 6.92 KB
/
neural_network.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
"""
This module implements the neural network class and all components necessary to
modularize the build/use process of the neural network.
"""
import numpy as np
import pickle
import os
import h5py
# create NN using Keras
from keras.models import Sequential, load_model
from keras.layers import Activation
from keras.optimizers import SGD
from keras.layers import Dense
from keras.utils import np_utils
from keras import initializers
# fix random seed for reproducibility
np.random.seed()
class NeuralNet:
def __init__(self, layers=None, activation_fns=None, model_file=None, bias = False):
if model_file != None:
self.model = load_model(model_file)
else:
self.model = Sequential()
self.model.add(Dense(layers[0], input_dim=2, init=initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None), activation=activation_fns[0], use_bias=False))
self.model.add(Dense(layers[1], init="random_uniform", activation=activation_fns[0]))
self.model.add(Dense(layers[2]))
self.model.add(Activation(activation_fns[1]))
self.model.compile(loss='mean_squared_error', optimizer='rmsprop')
def output(self, input):
pred = self.model.predict(np.array([np.array(input)]).reshape((1,2)))[0]
pred = [1 if i == max(pred) else 0 for i in pred]
return pred
# return [1., 0, 0, 0]
def get_all_weights(self):
# need weights of layers 1 & 2 - everything except first and last
w = []
# # print "No of layers: ", len(self.model.layers)
for i in xrange(1,len(self.model.layers)-1):
# # print self.model.layers[i].get_weights()
w.append(self.model.layers[i].get_weights())
return w
def set_all_weights(self, weights):
for i in xrange(1,len(self.model.layers)-1):
# w = np.array(weights[i-1])
self.model.layers[i].set_weights(weights[i-1])
# class NNetwork:
# """
# The representation of a feed forward neural network with a bias in every
# layer (excluding output layer obviously).
# """
# def __init__(self, layer_sizes, activation_funcs, bias_neuron = False):
# """
# Creates a 'NNetwork'. 'layer_sizes' provides information about the
# number of neurons in each layer, as well as the total number of layers
# in the neural network. 'activation_funcs' provides information about the
# activation functions to use on each respective hidden layers and output
# layer. This means that the length of 'activation_funcs' is always one
# less than the length of 'layer_sizes'.
# """
# assert(len(layer_sizes) >= 2)
# assert(len(layer_sizes) - 1 == len(activation_funcs))
# assert(min(layer_sizes) >= 1)
# self.layers = []
# self.connections = []
# # Initialize layers.
# for i in range(len(layer_sizes)):
# # Input layer.
# if i == 0:
# self.layers.append(Layer(layer_sizes[i], None, bias_neuron))
# # Hidden layer.
# elif i < len(layer_sizes) - 1:
# self.layers.append(Layer(layer_sizes[i], activation_funcs[i - 1], bias_neuron))
# # Output layer.
# else:
# self.layers.append(Layer(layer_sizes[i], activation_funcs[i - 1]))
# # Initialize connections.
# num_connections = len(layer_sizes) - 1
# for i in range(num_connections):
# self.connections.append(Connection(self.layers[i], self.layers[i + 1]))
# def feed_forward(self, data, one_hot_encoding = True):
# """
# Feeds given data through neural network and stores output in output
# layer's data field. Output can optionally be one-hot encoded.
# """
# if self.layers[0].HAS_BIAS_NEURON:
# assert(len(data) == self.layers[0].SIZE - 1)
# self.layers[0].data = data
# self.layers[0].data.append(1)
# else:
# assert(len(data) == self.layers[0].SIZE)
# self.layers[0].data = data
# for i in range(len(self.connections)):
# self.connections[i].TO.data = np.dot(self.layers[i].data, self.connections[i].weights)
# self.connections[i].TO.activate()
# if one_hot_encoding:
# this_data = self.layers[len(self.layers) - 1].data
# MAX = max(this_data)
# for i in range(len(this_data)):
# if this_data[i] == MAX:
# this_data[i] = 1
# else:
# this_data[i] = 0
# def output(self):
# """
# Retrieves data in output layer.
# """
# return self.layers[len(self.layers) - 1].data
# class Layer:
# """
# The representation of a layer in a neural network. Used as a medium for
# passing data through the network in an efficent manner.
# """
# def __init__(self, num_neurons, activation_func, bias_neuron = False):
# """
# Creates a 'Layer' with 'num_neurons' and an additional (optional) bias
# neuron (which always has a value of '1'). The layer will utilize the
# 'activation_func' during activation.
# """
# assert(num_neurons > 0)
# self.ACTIVATION_FUNC = activation_func
# self.HAS_BIAS_NEURON = bias_neuron
# if bias_neuron:
# self.SIZE = num_neurons + 1
# self.data = np.array([0] * num_neurons + [1])
# else:
# self.SIZE = num_neurons
# self.data = np.array([0] * num_neurons)
# def activate(self):
# """
# Calls activation function on layer's data.
# """
# if self.ACTIVATION_FUNC != None:
# self.ACTIVATION_FUNC(self.data)
# class Connection:
# """
# The representation of a connection between layers in a neural network.
# """
# def __init__(self, layer_from, layer_to):
# """"
# Creates a 'Connection' between 'layer_from' and 'layer_to' that contains
# all required weights, which are randomly initialized with random numbers
# in a guassian distribution of mean '0' and standard deviation '1'.
# """
# self.FROM = layer_from
# self.TO = layer_to
# self.weights = np.zeros((layer_from.SIZE, layer_to.SIZE))
# for i in range(layer_from.SIZE):
# for j in range(layer_to.SIZE):
# self.weights[i][j] = np.random.standard_normal()
# def sigmoid(data):
# """
# Uses sigmoid transformation on given data. This is an activation function.
# """
# for i in range(len(data)):
# data[i] = 1 / (1 + np.exp(-data[i]))
# def softmax(data):
# """
# Uses softmax transformation on given data. This is an activation function.
# """
# sum = 0.0
# for i in range(len(data)):
# sum += np.exp(data[i])
# for i in range(len(data)):
# data[i] = np.exp(data[i]) / sum