tensorflow base

 

 

import tensorflow as tf 

#定义两个常量操作
#构造函数返回的值就是常量节点(Constant op)的输出
a = tf.constant(2)
b = tf.constant(3)
#启动默认的计算图
with tf.Session() as sess:
    print("a = 2, b = 3")
    print("常量相加:{}".format(sess.run(a+b)))
    print("常量相乘:{}".format(sess.run(a*b))) 

#使用变量输出值作为计算图的输入
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
#定义一些操作
add = tf.add(a, b)
mul = tf.multiply(a, b)
#启动默认的计算图
with tf.Session() as sess:
    print("变量相加:{}".format(sess.run(add, feed_dict={a:2, b:3})))
    print("变量相乘:{}".format(sess.run(mul, feed_dict={a:2, b:3})))
    


#创建一个1X2的常量矩阵,该op会作为一个节点被加入到默认的计算图
#构造器返回的值代表这个op的输出
matrix1 = tf.constant([[3., 3.]])
#创建一个2X1的常量矩阵
matrix2 = tf.constant([[2.], [2.]])
#创建一个矩阵乘法op,它的输入为matrix1和matrix2
#返回的值product表示乘法的结果
product = tf.matmul(matrix1, matrix2)
#为了运行mutmul op我们运行会话的run()方法,使用product作为输入,product代表mutmul op的输出
#这表明我们想要matmul op的输出
#op的所有输入都会由会话自动运行。这些输入一般都是并行运行的
#对'run(product)'的调用回引起这3个op的执行:2个constants和一个matmul
#op的输出值返回给result,这是一个numpy数组对象
with tf.Session() as sess:
    result = sess.run(product)
    print("矩阵常量相称:{}".format(result))
    

# 与数据相关的op由三种: 
# - tf.constant 
# - tf.placeholder 
# - tf.Variable
#使用Variable的使用必须先经过初始化 (init) op 初始化
#注意不要使用tf.initialize_all_variables()了。否则会有警告,这个接口正在被抛弃
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    # 运行 'init' op
    sess.run(init_op)
    
    
# tf.assign(ref, value, validate_shape=None, use_locking=None, name=None)
# 函数完成了将value赋值给ref的作用
# 其中:ref 必须是tf.Variable创建的tensor,如果ref=tf.constant()会报错!同时,shape(value)==shape(ref)

    
    
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
# 创建一个 op, 其作用是使 state 增加 1
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.global_variables_initializer()
# 启动图, 运行 op
with tf.Session() as sess:
    # 运行 'init' op
    sess.run(init_op)
    # 打印 'state' 的初始值
    print(sess.run(state))
    # 运行 op, 更新 'state', 并打印 'state'
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
#输出0 1 2 3


#在之前的例子里, 我们只取回了单个节点 state, 但是你也可以取回多个 tensor
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
multiplication = tf.multiply(input1, intermed)
with tf.Session() as sess:
    result = sess.run([multiplication, intermed])
    print(result)
#输出
#[21.0, 7.0]

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
    #这说明feed机制提供了一种“打桩”的机制,我们可以任意控制节点的输出张量
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]})) # [array([14.], dtype=float32)]
    print(sess.run(output, feed_dict={input1:[7.], input2:[2.]})) # [14.]

a = 2, b = 3
常量相加:5
常量相乘:6
变量相加:5
变量相乘:6
矩阵常量相称:[[12.]]
0
1
2
3
[21.0, 7.0]
[array([14.], dtype=float32)]
[14.]

posted @ 2019-05-20 13:50  牧 天  阅读(493)  评论(0)    收藏  举报