Tensorflow--useful function

来源:互联网 发布:c罗会说几种语言 编辑:程序博客网 时间:2024/05/17 00:05
# The use of tf.assign() function, the validate_shape parameter is usefulb = tf.Variable([[4],[5],[6]], dtype=tf.float64, name='variable_b')print(b)with tf.Session() as sess:    sess.run(b.initializer)    print(sess.run(b))    b_assign = tf.assign(b, [1,2,3], validate_shape=False)    print(sess.run(b_assign))<tf.Variable 'variable_b_9:0' shape=(3, 1) dtype=float64_ref>[[ 4.] [ 5.] [ 6.]][ 1.  2.  3.]# Use the variable in the graph as any tensor, the arithmetic of matrixy = tf.matmul(w, x, name='multiply_wx');print(y)Tensor("multiply_wx_1:0", shape=(3, 1), dtype=float64)# initialize all variables in the graphinit_op = tf.global_variables_initializer()# Create a sessionwith tf.Session() as sess:    # Run the Op that initializes global variables    sess.run(init_op)# some math functiontf.sigmoid(w + y)tf.add# reduce_mean() function can reduce the dimensionsx = tf.Variable([[1,1],                 [2,2]], dtype=tf.float64, name='variable_x');print(x)with tf.Session() as sess:    sess.run(x.initializer)    print(sess.run(tf.reduce_mean(x)))    print(sess.run(tf.reduce_mean(x,0)))    print(sess.run(tf.reduce_mean(x,1)))    print(sess.run(tf.reduce_mean(x,1, keep_dims=True)))<tf.Variable 'variable_x_3:0' shape=(2, 2) dtype=float64_ref>1.5[ 1.5  1.5][ 1.  2.][[ 1.] [ 2.]]# reduce_sum() function can reduce dimensionsy = tf.Variable([[1,1,1],                 [1,1,1]], dtype=tf.float64, name='variable_y');print(y)with tf.Session() as sess:    sess.run(y.initializer)    print(sess.run(tf.reduce_sum(y)))    print(sess.run(tf.reduce_sum(y,0)))    print(sess.run(tf.reduce_sum(y,1)))    print(sess.run(tf.reduce_sum(y,1, keep_dims=True)))<tf.Variable 'variable_y_6:0' shape=(2, 3) dtype=float64_ref>6.0[ 2.  2.  2.][ 3.  3.][[ 3.] [ 3.]]