Tensorflow神经网络框架(第二课 创建图-启动图-变量)

2-1-2-3创建图-启动图-变量Last Checkpoint: 上星期五14:28(unsaved changes) Logout
In [20]:
 
                
print("hello world")
hello world
In [21]:
import tensorflow as tf
In [22]:
#创建两个常量op
m1 = tf.constant([[3,3]])
m2 = tf.constant([[2],[3]])
#创建一个矩阵乘法op,把m1和m2传入
product = tf.matmul(m1,m2)
print(product)
Tensor("MatMul_2:0", shape=(1, 1), dtype=int32)
In [23]:
#第2—1课 : 创建图,启动图
#定义一个会话,启动默认图
sess = tf.Session()
#调用sess的run方法来执行矩阵乘法op
#run(product)触发了图中3个op
result = sess.run(product)
print(result)
sess.close()
[[15]]
In [24]:
with tf.Session() as sess:
    #调用sess的run方法来执行矩阵乘法op
    #run(product)触发了图中3个op
    result = sess.run(product)
    print(result)
    #这里就不用关闭会话,系统自动关闭
[[15]]
In [25]:
#第2—2课 : 变量
x = tf.Variable([1,2])
a = tf.constant([3,3])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,sub)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))
[-2 -1]
[-1  1]
In [26]:
#创建一个变量初始化为0
state = tf.Variable(0,name='counter') #起名字
#创建一个op,作用是使state + 1
new_value = tf.add(state,1)
#赋值op
update = tf.assign(state,new_value)
#因为我们使用了变量,所以需要变量初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))
        
0
1
2
3
4
5
In [27]:
#第2—3课 : Fetch and Feed
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input1,input2)
mul = tf.multiply(input1,add)
#
with tf.Session() as sess:
    result = sess.run([mul,add])#同时执行多个op
    print(result)
[15.0, 5.0]
In [28]:
#Feed
#创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
#运行op时才传入变量的值
with tf.Session() as sess:
    #feed的数据以字典的形式传入
    print(sess.run(output,feed_dict={input1:[8.],input2:[2.]}))
[16.]
In [ ]:

猜你喜欢

转载自blog.csdn.net/u011473714/article/details/80804436