【tensorflow】基本使用

来源:互联网 发布:游戏开发编程语言 编辑:程序博客网 时间:2024/06/05 10:59

本系列使用的是tensorflow0.12和极客学院的中文教程有出入

import tensorflow as tfstate=tf.Variable(0,name="counter")#使用tensorflow在默认的图中创建节点,这个节点是一个变量one=tf.constant(1)new_value=tf.add(state,one)#对常量与变量进行简单的加法操作update=tf.assign(state, new_value)#赋值操作。将new_value的值赋值给state变量,返回值=new_value赋给updatainit_op=tf.global_variables_initializer()#之前只是定义好了图,并没有变量并没有初始化with tf.Session()  as sess:    print(sess.run(init_op))    print("new_value",sess.run(new_value))#0+1    print("state",sess.run(state))#初始化的0    print("------")    for _ in range(3):        print("update",sess.run(update))#赋值更新操作。将new_value的值赋值给update,state变量。        print("new_value",sess.run(new_value))#state+one        print("state",sess.run(state))        print("------")

输出:

Nonenew_value 1state 0------update 1new_value 2state 1------update 2new_value 3state 2------update 3new_value 4state 3------
输出多个值
import tensorflow as tfinput1 = tf.constant(3.0)input2 = tf.constant(2.0)input3 = tf.constant(5.0)intermed = tf.add(input2, input3)mul = tf.mul(input1, intermed)with tf.Session() as sess:  result = sess.run([mul, intermed])  print(result)

[21.0, 7.0]
使用placeholder作为占位符
import tensorflow as tfinput1 = tf.constant(3.0)input2 = tf.placeholder(tf.float32)input3 = tf.constant(5.0)intermed = tf.add(input2, input3)mul = tf.mul(input1, intermed)with tf.Session() as sess:  result = sess.run([mul], feed_dict={input2:[7.]})  print(result)

[array([ 36.], dtype=float32)]

原创粉丝点击