π The CoCalc Library - books, templates and other resources
License: OTHER
""" Some simple TensorFlow's ops1Author: Chip Huyen2Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"3cs20si.stanford.edu4"""5import os6os.environ['TF_CPP_MIN_LOG_LEVEL']='2'78import numpy as np9import tensorflow as tf101112a = tf.constant(2)13b = tf.constant(3)14x = tf.add(a, b)15with tf.Session() as sess:16writer = tf.summary.FileWriter('./graphs', sess.graph)17print(sess.run(x))18writer.close() # close the writer when youβre done using it192021a = tf.constant([2, 2], name='a')22b = tf.constant([[0, 1], [2, 3]], name='b')23x = tf.multiply(a, b, name='dot_product')24with tf.Session() as sess:25print(sess.run(x))26# >> [[0 2]27# [4 6]]2829tf.zeros(shape, dtype=tf.float32, name=None)30#creates a tensor of shape and all elements will be zeros (when ran in session)3132x = tf.zeros([2, 3], tf.int32)33y = tf.zeros_like(x, optimize=True)34print(y)35print(tf.get_default_graph().as_graph_def())36with tf.Session() as sess:37y = sess.run(y)383940with tf.Session() as sess:41print(sess.run(tf.linspace(10.0, 13.0, 4)))42print(sess.run(tf.range(5)))43for i in np.arange(5):44print(i)4546samples = tf.multinomial(tf.constant([[1., 3., 1]]), 5)4748with tf.Session() as sess:49for _ in range(10):50print(sess.run(samples))5152t_0 = 1953x = tf.zeros_like(t_0) # ==> 054y = tf.ones_like(t_0) # ==> 15556with tf.Session() as sess:57print(sess.run([x, y]))5859t_1 = ['apple', 'peach', 'banana']60x = tf.zeros_like(t_1) # ==> ['' '' '']61y = tf.ones_like(t_1) # ==> TypeError: Expected string, got 1 of type 'int' instead.6263t_2 = [[True, False, False],64[False, False, True],65[False, True, False]]66x = tf.zeros_like(t_2) # ==> 2x2 tensor, all elements are False67y = tf.ones_like(t_2) # ==> 2x2 tensor, all elements are True68with tf.Session() as sess:69print(sess.run([x, y]))7071with tf.variable_scope('meh') as scope:72a = tf.get_variable('a', [10])73b = tf.get_variable('b', [100])7475writer = tf.summary.FileWriter('test', tf.get_default_graph())767778x = tf.Variable(2.0)79y = 2.0 * (x ** 3)80z = 3.0 + y ** 281grad_z = tf.gradients(z, [x, y])82with tf.Session() as sess:83sess.run(x.initializer)84print(sess.run(grad_z))858687