-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensorflow_practice2.py
More file actions
57 lines (42 loc) · 1.46 KB
/
tensorflow_practice2.py
File metadata and controls
57 lines (42 loc) · 1.46 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
import numpy as np
from sklearn.utils import shuffle
import tensorflow as tf
M = 2
K = 3
n = 100
N = n * K
X1 = np.random.randn(n, M) + np.array([0, 10])
X2 = np.random.randn(n, M) + np.array([5, 5])
X3 = np.random.randn(n, M) + np.array([10, 0])
Y1 = np.array([[1, 0, 0] for i in range(n)])
Y2 = np.array([[0, 1, 0] for i in range(n)])
Y3 = np.array([[0, 0, 1] for i in range(n)])
X = np.concatenate((X1, X2, X3), axis=0)
Y = np.concatenate((Y1, Y2, Y3), axis=0)
W = tf.Variable(tf.zeros([M, K]))
b = tf.Variable(tf.zeros([K]))
x = tf.placeholder(tf.float32, shape=[None, M])
t = tf.placeholder(tf.float32, shape=[None, K])
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(t * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(t, 1))
batch_size = 50
n_batches = N // batch_size
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for epoch in range(20):
X_, Y_ = shuffle(X, Y)
for i in range(n_batches):
start = i * batch_size
end = start * batch_size
sess.run(train_step, feed_dict={x: X_[start:end], t: Y_[start:end]})
X_, Y_ = shuffle(X, Y)
classifed = correct_prediction.eval(session=sess, feed_dict={x: X_[0:10], t: Y_[0:10]})
prob = y.eval(session=sess, feed_dict={x: X_[0:10]})
print('classifed:')
print(classifed)
print()
print('output probability:')
print(prob)