tensorflow 2.0版学习

一、session会话
1.第一种方式

import tensorflow.compat.v1 as tf
tf.disable_eager_execution() #保证sess.run()能够正常运行

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
				   [2]])
product = tf.matmul(matrix1,matrix2)
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()

2.第二种方式

import tensorflow.compat.v1 as tf
tf.disable_eager_execution() #保证sess.run()能够正常运行

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
				   [2]])
product = tf.matmul(matrix1,matrix2)
with tf.Session() as sess:
  result2 = sess.run(product)
  print(result2)

二、变量

import tensorflow.compat.v1 as tf
"此处与tensorflow1.0版本不同 1.0为import tensorflow as tf"
tf.disable_eager_execution() #保证session的运行
"此处与tensorflow1.0版本不同 "
state = tf.Variable(0,name='counter') #计数变量,所以讲state命名为counter
one = tf.constant(1)

new_value=tf.add(state,one) #变量加常量
update = tf.assign(state,new_value) #将变量加载到state上

init = tf.global_variables_initializer() #如果有变量被定义,必须要进行的操作
"此处与tensorflow1.0版本不同:tf.initialize_all_variables()"
with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

三、placeholder传入值

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
input1 = tf.placeholder(tf.float32) #一般情况下只能float32
# input1 = tf.placeholder(tf.float32,[2,2]) #[2,2]表示结构为两行两列
input2 = tf.placeholder(tf.float32)

output = tf.multiply(input1,input2) #乘法运算

with tf.Session() as sess:
    print(sess.run(output,feed_dict={
    
    input1:[7.],input2:[2.]}))#运算output

本文是学习莫烦PYTHON之后的笔记
https://www.bilibili.com/video/BV1Lx411j7ws?p=12

猜你喜欢

转载自blog.csdn.net/up_and_down__/article/details/119759615