-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnn.py
157 lines (125 loc) · 5.95 KB
/
nn.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
# coding=utf-8
import tensorflow as tf
import numpy as np
import string
import random
TARGET_ERROR = 0.1
INPUT_FILE = "Input/letters.txt"
DELIMITER = " "
INPUT_LAYER_WIDTH = 5
INPUT_LAYER_HEIGHT = 7
OUTPUT_LAYER_WIDTH = 1
OUTPUT_LAYER_HEIGHT = 26
ALPHABET = list(string.ascii_uppercase)
MAX_ITERATIONS = 30000
def one_hot(l, n):
"""Returns an array of arrays of zeros, each internal array with one 1 (the element of the list)"""
if type(l) == list:
l = np.array(l)
l = l.flatten()
o_h = np.zeros((len(l), n))
o_h[np.arange(len(l)), l] = 1
return o_h
def get_pattern(pattern, width, height):
"""Returns the pattern in a string of width*height figure"""
if len(pattern) != width * height:
raise Exception("len(pattern) != width*height")
result = ""
for row in range(height):
for column in range(width):
result += ' ' if pattern[row * width + column] == 0 else '·'
result += '\n'
return result
def add_noise(data, noise_ratio):
swap_value = (lambda x: 1 if x == 0 else 0)
swap_if_random = (lambda x: swap_value(x) if random.random() < noise_ratio else x)
check_every_value = (lambda x: list(map(swap_if_random, x)))
return list(map(check_every_value, data))
def net_1capa(learning_rate, number_of_hidden_elements, noise, func, momentum=0.9, ele=2):
if func==2:
print("net(%f, %d mom:%f)" % (learning_rate, number_of_hidden_elements, momentum))
else:
print("net(%f, %d)" % (learning_rate, number_of_hidden_elements))
data = np.genfromtxt(INPUT_FILE, delimiter=DELIMITER, dtype=int)
np.random.shuffle(data)
x_data = data[:, 0:35]
# y_data = x_data
y_data = one_hot(data[:, 35], 26)
x = tf.placeholder(tf.float32, [None, INPUT_LAYER_WIDTH * INPUT_LAYER_HEIGHT])
y_ = tf.placeholder(tf.float32, [None, OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT])
"Initialization of weights for hidden and output layers"
w1 = tf.Variable(
np.float32(np.random.rand(INPUT_LAYER_WIDTH * INPUT_LAYER_HEIGHT, number_of_hidden_elements)) * 0.1)
w2 = tf.Variable(
np.float32(np.random.rand(number_of_hidden_elements, OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT)) * 0.1)
"Initialization ob bias for hidden and output layers"
b1 = tf.Variable(np.float32(np.random.rand(number_of_hidden_elements)) * 0.1)
b2 = tf.Variable(np.float32(np.random.rand(OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT)) * 0.1)
"Output of hidden and output layers (activation function)"
y1 = tf.sigmoid(tf.matmul(x, w1) + b1)
y2 = tf.nn.softmax(tf.matmul(y1, w2) + b2)
"Function to reduce"
cross_entropy = tf.reduce_sum(tf.square(y_ - y2))
if func == 1:
train = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
else:
train = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(cross_entropy)
"TF initialization"
sess = tf.Session()
sess.run(tf.global_variables_initializer())
errors = [sess.run(cross_entropy, feed_dict={x: add_noise(x_data, noise), y_: y_data})]
"Training"
while errors[-1] > TARGET_ERROR and len(errors) < MAX_ITERATIONS:
sess.run(train, feed_dict={x: add_noise(x_data, noise), y_: y_data})
errors.append(sess.run(cross_entropy, feed_dict={x: add_noise(x_data, noise), y_: y_data}))
if len(errors) >= MAX_ITERATIONS:
return -1
else:
return len(errors)
def net_2capas(learning_rate, number_of_elements_layer1, noise, func, momentum=0.9, number_of_elements_layer2=None):
if number_of_elements_layer2 is None:
number_of_elements_layer2 = number_of_elements_layer1
if func == 2:
print("net(%f, %d,%d mom:%f)" % (learning_rate, number_of_elements_layer1, number_of_elements_layer2, momentum))
else:
print("net(%f, %d,%d)" % (learning_rate, number_of_elements_layer1, number_of_elements_layer2))
data = np.genfromtxt(INPUT_FILE, delimiter=DELIMITER, dtype=int)
np.random.shuffle(data)
x_data = data[:, 0:35]
# y_data = x_data
y_data = one_hot(data[:, 35], 26)
x = tf.placeholder(tf.float32, [None, INPUT_LAYER_WIDTH * INPUT_LAYER_HEIGHT])
y_ = tf.placeholder(tf.float32, [None, OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT])
"Initialization of weights for hidden and output layers"
w1 = tf.Variable(
np.float32(np.random.rand(INPUT_LAYER_WIDTH * INPUT_LAYER_HEIGHT, number_of_elements_layer1)) * 0.1)
w2 = tf.Variable(
np.float32(np.random.rand(number_of_elements_layer1, number_of_elements_layer2)) * 0.1)
w3 = tf.Variable(
np.float32(np.random.rand(number_of_elements_layer2, OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT)) * 0.1)
"Initialization ob bias for hidden and output layers"
b1 = tf.Variable(np.float32(np.random.rand(number_of_elements_layer1)) * 0.1)
b2 = tf.Variable(np.float32(np.random.rand(number_of_elements_layer2)) * 0.1)
b3 = tf.Variable(np.float32(np.random.rand(OUTPUT_LAYER_WIDTH * OUTPUT_LAYER_HEIGHT)) * 0.1)
"Output of hidden and output layers (activation function)"
y1 = tf.sigmoid(tf.matmul(x, w1) + b1)
y2 = tf.sigmoid(tf.matmul(y1, w2) + b2)
y3 = tf.nn.softmax(tf.matmul(y2, w3) + b3)
"Function to reduce"
cross_entropy = tf.reduce_sum(tf.square(y_ - y3))
if func == 1:
train = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
else:
train = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(cross_entropy)
"TF initialization"
sess = tf.Session()
sess.run(tf.global_variables_initializer())
errors = [sess.run(cross_entropy, feed_dict={x: add_noise(x_data, noise), y_: y_data})]
"Training"
while errors[-1] > TARGET_ERROR and len(errors) < MAX_ITERATIONS:
sess.run(train, feed_dict={x: add_noise(x_data, noise), y_: y_data})
errors.append(sess.run(cross_entropy, feed_dict={x: add_noise(x_data, noise), y_: y_data}))
if len(errors) >= MAX_ITERATIONS:
return -1
else:
return len(errors)