Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

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

Views: 96144
License: OTHER
1
""" Simple TensorFlow's ops
2
Created by Chip Huyen ([email protected])
3
CS20: "TensorFlow for Deep Learning Research"
4
cs20.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
# Example 1: Simple ways to create log file writer
13
a = tf.constant(2, name='a')
14
b = tf.constant(3, name='b')
15
x = tf.add(a, b, name='add')
16
writer = tf.summary.FileWriter('./graphs/simple', tf.get_default_graph())
17
with tf.Session() as sess:
18
# writer = tf.summary.FileWriter('./graphs', sess.graph)
19
print(sess.run(x))
20
writer.close() # close the writer when youโ€™re done using it
21
22
# Example 2: The wonderful wizard of div
23
a = tf.constant([2, 2], name='a')
24
b = tf.constant([[0, 1], [2, 3]], name='b')
25
26
with tf.Session() as sess:
27
print(sess.run(tf.div(b, a)))
28
print(sess.run(tf.divide(b, a)))
29
print(sess.run(tf.truediv(b, a)))
30
print(sess.run(tf.floordiv(b, a)))
31
# print(sess.run(tf.realdiv(b, a)))
32
print(sess.run(tf.truncatediv(b, a)))
33
print(sess.run(tf.floor_div(b, a)))
34
35
# Example 3: multiplying tensors
36
a = tf.constant([10, 20], name='a')
37
b = tf.constant([2, 3], name='b')
38
39
with tf.Session() as sess:
40
print(sess.run(tf.multiply(a, b)))
41
print(sess.run(tf.tensordot(a, b, 1)))
42
43
# Example 4: Python native type
44
t_0 = 19
45
x = tf.zeros_like(t_0) # ==> 0
46
y = tf.ones_like(t_0) # ==> 1
47
48
t_1 = ['apple', 'peach', 'banana']
49
x = tf.zeros_like(t_1) # ==> ['' '' '']
50
# y = tf.ones_like(t_1) # ==> TypeError: Expected string, got 1 of type 'int' instead.
51
52
t_2 = [[True, False, False],
53
[False, False, True],
54
[False, True, False]]
55
x = tf.zeros_like(t_2) # ==> 3x3 tensor, all elements are False
56
y = tf.ones_like(t_2) # ==> 3x3 tensor, all elements are True
57
58
print(tf.int32.as_numpy_dtype())
59
60
# Example 5: printing your graph's definition
61
my_const = tf.constant([1.0, 2.0], name='my_const')
62
print(tf.get_default_graph().as_graph_def())
63