因需求需要用到些Tensorflow的知识,所以简单入门一下
首先我们去安装tensorflow,tensorflow有CPU版本和GPU版本有关tensorflow的安装可以看这个视频,讲解的很好tensorflow2.0的安装
安装好后我们进行代码操作
import tensorflow as tf
a = tf.constant(2.5) # 定义一个常量,给a赋值为2.5
print(a)
b = tf.Variable(10, name="var") # 定义一个变量,初始值10,名字为var
print(b)
分别定义了一个常亮和一个变量,但是打印出来确实类型的解释,tensorflow的数据都要放到session会话中执行
import tensorflow.compat.v1 as tf # 如果是tensorflow2.0这么写 而 tensorflow 1.x写作 import tensorflow as tf
tf.disable_v2_behavior() # 表示继续使用1.x版本的语法
a = tf.constant(2.5) # 定义一个常量,给a赋值为2.5
print(a)
b = tf.Variable(10, name="var") # 定义一个变量,初始值10,名字为var
print(b)
sess = tf.Session() #创建session会话
print(sess.run(a))
sess.close() # 关闭session
可以看到打印了2.5
我们也可以给他指定数据类型如下
a = tf.constant(2, dtype=tf.int32)
但是我们打印这个变量b却是报错的,那是因为变量在tensorflow中都要进行初始化
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(b))
我们也可以用with as来创建session
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
a = tf.constant(3.4)
b = tf.Variable(12)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(a))
print(sess.run(b))
tensorflow四则运算
常量的计算
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
a = tf.constant(8)
b = tf.constant(2)
x1 = tf.add(a, b)
x2 = tf.multiply(a, b)
x3 = tf.subtract(a, b)
x4 = tf.divide(a, b)
with tf.Session() as sess:
print(sess.run(x1))
print(sess.run(x2))
print(sess.run(x3))
print(sess.run(x4))
变量的运算
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
a = tf.constant(8)
b = tf.Variable(2)
init = tf.global_variables_initializer()
x1 = tf.add(a, b)
x2 = tf.multiply(a, b)
x3 = tf.subtract(a, b)
x4 = tf.divide(a, b)
with tf.Session() as sess:
sess.run(init)
print(sess.run(x1))
print(sess.run(x2))
print(sess.run(x3))
print(sess.run(x4))