-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuild a NN
More file actions
74 lines (60 loc) · 2.2 KB
/
Copy pathBuild a NN
File metadata and controls
74 lines (60 loc) · 2.2 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
# Buliding a sample of nerual network
import _future_ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Create a function of layer
def add_layer(inputs,in_size, out_size, activation_function=None):
Weights = tf.Varibles(tf.random_normal([in_size, out_size]))
biases = tf.Varibles(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
## Set up data and structure
# Make up some real data
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis] # column vector
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
# Plot scatter of x and y
# plt.scatter(x_data, y_data)
# plt.show()
# Define placeholder for input to network
xs = tf.placeholder(tf.float32, [None,1])
ys = tf.placeholder(tf.float32, [None,1])
# Add hidden layer
L1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# Add output layer
prediction = add_layer(L1, 10, 1, activation_function=None)
# The error between prediction and real data
learning_rate = 0.1
diff = tf.square(ys-prediction)
loss = tf.reduce_mean(tf.reduce_sum(diff, reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
## Set up computation part in session to activate the part of data and structure
# Important step, never forget
sess = tf.Session()
init = tf.global_variables_initializer()
see.run(init)
## Training
# Plot the real data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
# Visualize the result and improvement
try:
ax.line.remove(line[0])
except Exception
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
# Plot the prediction
line = ax.plot(x_data, prediction_value, 'r', lw=5)
plit.pasue(0.1)