π The CoCalc Library - books, templates and other resources
License: OTHER
""" Simple TensorFlow's ops1Created by Chip Huyen ([email protected])2CS20: "TensorFlow for Deep Learning Research"3cs20.stanford.edu4"""5import os6os.environ['TF_CPP_MIN_LOG_LEVEL']='2'78import numpy as np9import tensorflow as tf1011# Example 1: Simple ways to create log file writer12a = tf.constant(2, name='a')13b = tf.constant(3, name='b')14x = tf.add(a, b, name='add')15writer = tf.summary.FileWriter('./graphs/simple', tf.get_default_graph())16with tf.Session() as sess:17# writer = tf.summary.FileWriter('./graphs', sess.graph)18print(sess.run(x))19writer.close() # close the writer when youβre done using it2021# Example 2: The wonderful wizard of div22a = tf.constant([2, 2], name='a')23b = tf.constant([[0, 1], [2, 3]], name='b')2425with tf.Session() as sess:26print(sess.run(tf.div(b, a)))27print(sess.run(tf.divide(b, a)))28print(sess.run(tf.truediv(b, a)))29print(sess.run(tf.floordiv(b, a)))30# print(sess.run(tf.realdiv(b, a)))31print(sess.run(tf.truncatediv(b, a)))32print(sess.run(tf.floor_div(b, a)))3334# Example 3: multiplying tensors35a = tf.constant([10, 20], name='a')36b = tf.constant([2, 3], name='b')3738with tf.Session() as sess:39print(sess.run(tf.multiply(a, b)))40print(sess.run(tf.tensordot(a, b, 1)))4142# Example 4: Python native type43t_0 = 1944x = tf.zeros_like(t_0) # ==> 045y = tf.ones_like(t_0) # ==> 14647t_1 = ['apple', 'peach', 'banana']48x = tf.zeros_like(t_1) # ==> ['' '' '']49# y = tf.ones_like(t_1) # ==> TypeError: Expected string, got 1 of type 'int' instead.5051t_2 = [[True, False, False],52[False, False, True],53[False, True, False]]54x = tf.zeros_like(t_2) # ==> 3x3 tensor, all elements are False55y = tf.ones_like(t_2) # ==> 3x3 tensor, all elements are True5657print(tf.int32.as_numpy_dtype())5859# Example 5: printing your graph's definition60my_const = tf.constant([1.0, 2.0], name='my_const')61print(tf.get_default_graph().as_graph_def())6263