-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_computations.py
executable file
·94 lines (54 loc) · 1.48 KB
/
simple_computations.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
#!/usr/bin/env python
import tensorflow as tf
a = tf.constant(1)
b = tf.constant(2)
c = a + b
d = a * b
V1 = tf.constant([1.,2.])
V2 = tf.constant([3.,4.])
M = tf.constant([[1.,2.]]) # Matrix, 2d
N = tf.constant([[1.,2.],[3.,4.]]) # Matrix, 2d
K = tf.constant([[[1.,2.],[3.,4.]]]) #Tensor, 3d+
# You can also compute on tensors
V3 = V1 + V2
# Operations are element-wise by default
M2 = M * M
# True matrix multiplication requires a Special Call
NN = tf.matmul(N,N)
# The above code only defines a TF "graph"
# Nothing has been computed yet
# For that, you first need to create a TF "session"
sess = tf.Session()
output = sess.run(NN)
print("NN is:")
print(output)
sess.close()
sess = tf.InteractiveSession()
print("M2 is:")
print(M2.eval())
# TF "variables" can change value
# useful for updating model weights
W = tf.Variable(0, name="weight")
# But variables must be initialized by TF before use
init_op = tf.initialize_all_variables()
sess.run(init_op)
print("W is:")
print(W.eval())
W += a
print("W after adding a:")
print(W.eval())
W += a
print("W after adding a again:")
print(W.eval())
# You can return or supply arbitrary nodes,
# i.e. check an intermediate value or
# sub your value in the middle of a computation
E = d + b # 1*2 + 2 = 4
print("E as defined")
print(E.eval())
# Let's see what d was at the same time
print("E and d:")
print(sess.run([E,d]))
# Use a custom d by specifying a dictionary
print("E with custom d=4")
print(sess.run(E, feed_dict = {d: 4}))