Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

πŸ“š The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
""" Some simple TensorFlow's ops
2
Author: Chip Huyen
3
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
4
cs20si.stanford.edu
5
"""
6
import os
7
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
8
9
import numpy as np
10
import tensorflow as tf
11
12
13
a = tf.constant(2)
14
b = tf.constant(3)
15
x = tf.add(a, b)
16
with tf.Session() as sess:
17
writer = tf.summary.FileWriter('./graphs', sess.graph)
18
print(sess.run(x))
19
writer.close() # close the writer when you’re done using it
20
21
22
a = tf.constant([2, 2], name='a')
23
b = tf.constant([[0, 1], [2, 3]], name='b')
24
x = tf.multiply(a, b, name='dot_product')
25
with tf.Session() as sess:
26
print(sess.run(x))
27
# >> [[0 2]
28
# [4 6]]
29
30
tf.zeros(shape, dtype=tf.float32, name=None)
31
#creates a tensor of shape and all elements will be zeros (when ran in session)
32
33
x = tf.zeros([2, 3], tf.int32)
34
y = tf.zeros_like(x, optimize=True)
35
print(y)
36
print(tf.get_default_graph().as_graph_def())
37
with tf.Session() as sess:
38
y = sess.run(y)
39
40
41
with tf.Session() as sess:
42
print(sess.run(tf.linspace(10.0, 13.0, 4)))
43
print(sess.run(tf.range(5)))
44
for i in np.arange(5):
45
print(i)
46
47
samples = tf.multinomial(tf.constant([[1., 3., 1]]), 5)
48
49
with tf.Session() as sess:
50
for _ in range(10):
51
print(sess.run(samples))
52
53
t_0 = 19
54
x = tf.zeros_like(t_0) # ==> 0
55
y = tf.ones_like(t_0) # ==> 1
56
57
with tf.Session() as sess:
58
print(sess.run([x, y]))
59
60
t_1 = ['apple', 'peach', 'banana']
61
x = tf.zeros_like(t_1) # ==> ['' '' '']
62
y = tf.ones_like(t_1) # ==> TypeError: Expected string, got 1 of type 'int' instead.
63
64
t_2 = [[True, False, False],
65
[False, False, True],
66
[False, True, False]]
67
x = tf.zeros_like(t_2) # ==> 2x2 tensor, all elements are False
68
y = tf.ones_like(t_2) # ==> 2x2 tensor, all elements are True
69
with tf.Session() as sess:
70
print(sess.run([x, y]))
71
72
with tf.variable_scope('meh') as scope:
73
a = tf.get_variable('a', [10])
74
b = tf.get_variable('b', [100])
75
76
writer = tf.summary.FileWriter('test', tf.get_default_graph())
77
78
79
x = tf.Variable(2.0)
80
y = 2.0 * (x ** 3)
81
z = 3.0 + y ** 2
82
grad_z = tf.gradients(z, [x, y])
83
with tf.Session() as sess:
84
sess.run(x.initializer)
85
print(sess.run(grad_z))
86
87