TensorFlow 2.0系列相对与1.x系列有了许多变化,像Tensorflow 1.x系列要使用会话tf.Session(),然而在Tensorflow2.x系列却没有会话的属性。现在开始了解Tensorflow的数据类型和基本运算。
import tensorflow as tf
'''
v1.x转换v2.0
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
'''
#创建常量t
t=tf.constant('hello tensorflow',dtype=tf.string)
print(t)
# tf.Tensor(b'hello tensorflow', shape=(), dtype=string)
#创建变量
a=tf.Variable(5.2,dtype=tf.float16)
b=tf.Variable(3.6,dtype=tf.float16)
print(a)
# <tf.Variable 'Variable:0' shape=() dtype=float16, numpy=5.2>
#输出变量的值
print(a.numpy())
# 5.2
#创建张量
M1=tf.Variable([2.5,3.6],dtype=tf.float32)
print(M1)
# <tf.Variable 'Variable:0' shape=(2,) dtype=float32, numpy=array([2.5, 3.6], dtype=float32)>
print(M1.numpy())
# [2.5 3.6]
#创建矩阵
M2=tf.Variable(tf.ones((2,5)),dtype=tf.float32)
print(M2)
# <tf.Variable 'Variable:0' shape=(2, 5) dtype=float32, numpy=
# array([[1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.]], dtype=float32)>
print(M2.numpy())
#加减乘除运算(常规,张量,矩阵)
add_ab=tf.add(a,b)
print(add_ab)
# tf.Tensor(8.8, shape=(), dtype=float16)
mul_M1=tf.multiply(M1,M1)
print(mul_M1)
# tf.Tensor([ 6.25 12.959999], shape=(2,), dtype=float32)
add_M2=tf.add(M2,M2)
print(add_M2)
# tf.Tensor(
# [[2. 2. 2. 2. 2.]
# [2. 2. 2. 2. 2.]], shape=(2, 5), dtype=float32)