Tensorflow normal
import numpy as np import tensorflow as tf def main(): testNormal() testPlaceholder() testPlaceholder1() test3() testGet_tensor_by_name() def testNormal(): #tf.random_uniform((4, 4), minval=low,maxval=high,dtype=tf.float32)))返回4*4的矩阵,产生于low和high之间,产生的值是均匀分布的。 #sq = tf.square(tf.constant([2, 4, 6, 8])) sq1 = tf.random_uniform((2, 2), -1, 1) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) #print(sess.run(sq)) # [ 4 16 36 64] print(sess.run(sq1)) sess.close() def testPlaceholder1(): input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.multiply(input1, input2) with tf.Session() as sess: print(sess.run([output], feed_dict={input1:7., input2:2.})) print(sess.run([output], feed_dict={input1:[7.], input2:[2.]})) #A Simple TensorFlow example #用Tensorflow计算a=(b+c)∗(c+2) def testPlaceholder(): #1. 定义数据: # 首先,创建一个TensorFlow常量=>2 const = tf.constant(2.0, name='const') # 创建TensorFlow变量b和c #b = tf.Variable(2.0, name='b') # 创建placeholder # TensorFlow 还提供了 feed机制, 该机制 可以临时替代图中的任意操作中的 tensor #可以对图中任何操作提交补丁, 直接插入一个 tensor. b = tf.placeholder(tf.float32, [None, 1], name='b') c = tf.Variable(1.0, dtype=tf.float32, name='c') #2. 定义运算(也称TensorFlow operation): d = tf.add(b, c, name='d') e = tf.add(c, const, name='e') a = tf.multiply(d, e, name='a') #TensorFlow中所有的变量必须经过初始化才能使用,初始化方式分两步: #<1. 定义初始化operation init_op = tf.global_variables_initializer() # session with tf.Session() as sess: #<2. 运行init operation sess.run(init_op) # 计算 #a_out = sess.run(a) a_out = sess.run(a, feed_dict={b: np.arange(0, 10)[:, np.newaxis]}) print("Variable a is {}".format(a_out)) def test3(): a = tf.add(2, 5) #a=7 b = tf.multiply(a, 3) #b=3*7=21 with tf.Session() as sess: print(sess.run(b)) # 21 replace_dict = {a:15} #用15代替b算式中的a # TF Session.run注入参数简单例子, feed_dict参数的作用是替换图中的某个tensor的值。 print(sess.run(b, feed_dict = replace_dict)) #45 def testGet_tensor_by_name(): c = tf.placeholder(tf.float32, [2, 2], name='namec') d = tf.constant([[1.0, 1.0], [0.0, 1.0]]) e = tf.matmul(c, d, name='example') with tf.Session() as sess: result = sess.run(e, feed_dict={c : [[1, 1], [1, 1]]}) print(result) # [[1. 2.], [1. 2.]] print (e.name) #example:0 testc = tf.get_default_graph().get_tensor_by_name("namec:0") print(testc) print(sess.run(e, feed_dict={testc:[[1, 0], [0, 1]]})) #[[1. 1.], [0. 1.]] if __name__ == '__main__': main()
[[-0.22921348 0.68460655]
 [ 0.21008825 -0.75417924]]
Variable a is [[ 3.]
 [ 6.]
 [ 9.]
 [12.]
 [15.]
 [18.]
 [21.]
 [24.]
 [27.]
 [30.]]
[14.0]
[array([14.], dtype=float32)]
21
45
[[1. 2.]
 [1. 2.]]
example:0
Tensor("namec:0", shape=(2, 2), dtype=float32)
[[1. 1.]
 [0. 1.]]
                    
                
                
            
        
浙公网安备 33010602011771号