莫烦tensorflow学习记录 (1)session会话控制、variable变量、placeholder传入值

https://mofanpy.com/tutorials/machine-learning/tensorflow/session/

 

Session 会话控制

#https://mofanpy.com/tutorials/machine-learning/tensorflow/session/
import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
                       [2]])
product = tf.matmul(matrix1,matrix2) # 相乘,等于np.dot(m1,m2)

# ### method 1
# sess = tf.Session()
# result = sess.run(product)
# print(result)
# sess.close() #关闭Session

### method 2
with tf.Session() as sess: #打开Session并命名为sess ,运行到最后会自动关闭sess
    result2 = sess.run(product)
    print(result2)



"""哈哈,看看咱Tensorflow2.1的简洁,什么session,完全不需要的。"""

# import tensorflow as tf
#
# matrix1=tf.constant([[3,3]])
# matrix2=tf.constant([[2],[2]])
# product=tf.matmul(matrix1,matrix2)
# tf.print(product)

Variable 变量

import tensorflow as tf

state = tf.Variable(0,name='counter')
print(state.name)

#定义变量,节点
one = tf.constant(1) #one是个常数1
new_value = tf.add(state , one) # 定义加法步骤 (注: 此步并没有直接计算)
update = tf.assign(state,new_value) #new_value去更新state

#建立变量,之后用Session激活
#init = tf.initialize_all_tables() #tensorflow<0.12,用这行
init = tf.global_variables_initializer() #tensorflow>=0.12,用这行

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

print(state.name)
'''
如果在最后执行
print(state.name)
发现其实state本身并没有变,只是在Session这个会话中发生了变化,
可以理解为Session是一个单独的过程,对全局不造成影响
'''

#
# """
# 继续附上tensorflow2.1代码
# """
# import tensorflow as tf
#
# state = tf.Variable(1,name='counter')
# tf.print(state)
# one = tf.constant(1)
# new_value = tf.add(state,one)
# tf.print(state,new_value)
# for _ in range(3):
#     state.assign_add(new_value)
#     tf.print(state,new_value)

Placeholder 传入值

# https://mofanpy.com/tutorials/machine-learning/tensorflow/placeholde/
import tensorflow as tf

"""
这一次我们会讲到 Tensorflow 中的 placeholder , placeholder 是 Tensorflow 中的占位符,暂时储存变量.
Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **}).
"""
# input1 = tf.placeholder(tf.float32, [2,2]) #定义input为placeholder,结构为两行两列
# placeholder 实现后赋值,或者说是传入值
# 在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

# mul = multiply 是将input1和input2 做乘法运算,并输出为 output
output = tf.multiply(input1,input2)

with tf.Session() as sess:
    print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))# 在运行output的时候利用feed_dict将input的值赋值

# placeholder 是你输入自己数据的接口, variable 是网络自身的变量, 通常不是你来进行修改, 而是网络自身会改动更新.

 

posted @ 2020-10-12 10:11  薄书  阅读(159)  评论(0编辑  收藏  举报