【TensorFlow2.x系列第1篇】TensorFlow2.0-基本语法与运算

第一篇(语法必备)

TensorFlow 2.0系列相对与1.x系列有了一些明显的变化,比如1.x系列要使用会话tf.Session(),然而在tensorflow2.x系列却没有会话的属性,这是比较明显的变化,另外2.x比1.x的使用也灵活了很多,2.x系列可以在张量tensor和numpy类型之间灵活使用,这也是比较友好的,下面详细tensorflow2.0系列基本语法如下文介绍。

常量/变量

### 常量
import tensorflow as tf

w = tf.constant(3, dtype=tf.float32)
print(w)
#out:<tf.Tensor: id=536, shape=(), dtype=int32, numpy=3>
wM = tf.constant(tf.ones((3,4)), dtype=tf.float32)
#out:<tf.Tensor: id=540, shape=(3, 4), dtype=float32, numpy=
#array([[1., 1., 1., 1.],
#       [1., 1., 1., 1.],
#       [1., 1., 1., 1.]], dtype=float32)>

### 变量单一值
w = tf.Variable(2.0, dtype=tf.float32)
# 输出张量 tensor
print(w)
#out:<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>
# 输出数值 numpy
print(w.numpy())
#out:2.0

向量/矩阵

### 向量
import tensorflow as tf

wV = tf.Variable([2.3,1.3], dtype=tf.float32)
# 输出张量 tensor
print(wV)
#out:<tf.Variable 'Variable:0' shape=(2,) dtype=float32, numpy=array([2.3, 1.3], dtype=float32)>
# 输出数值 numpy
print(wV.numpy())
#out:array([2.3, 1.3], dtype=float32)

### 矩阵
wM = tf.Variable(tf.ones((3,2)), dtype=tf.float32)
# 输出张量 tensor
print(wV)
#out:<tf.Variable 'Variable:0' shape=(3, 2) dtype=float32, numpy=
#        array([[1., 1.],
#               [1., 1.],
#               [1., 1.]], dtype=float32)>
# 输出数值 numpy
print(wV.numpy())
#out:array([[1., 1.],
#       [1., 1.],
#       [1., 1.]], dtype=float32)

常规运算

加减乘除

###################################### 练习1
# 计算 y = (wx + b - c)/d,其中 w=2.0, x=5, b=1, c = 1, d=2, 计算 y
import tensorflow as tf

w = tf.Variable(2.0, dtype=tf.float32)
x = tf.Variable(5.0, dtype=tf.float32)
b = tf.Variable(1.0, dtype=tf.float32)
c = tf.Variable(1.0, dtype=tf.float32)
d = tf.Variable(2.0, dtype=tf.float32)

wx = tf.multiply(w,x)  # 乘法
wxb  = tf.add(wx,b)  # 加法
wxbc = tf.subtract(wxb,c)  # 减法
wxbcd = tf.divide(wxbc,d)  # 除法

print('Out y tensor:%s'%(wxbcd))
print('Out y numpy value:{yV}'.format(yV=wxbcd.numpy()))
#out:Out y tensor:tf.Tensor(5.0, shape=(), dtype=float32)
#Out y numpy value:5.0

向量运算

###################################### 练习2
# 计算 y = (wx + b - c)/d,其中,w = [1,2,3], x = [2,3,4], b = [1,1,2], c = [1,1,1], d = [2,2,2],计算 y
# 向量运算是对应位置相加减、乘除,两向量之间的维度要一致
# 向量运算与矩阵运算最大的不同是:向量运算要求运算向量之间的维度要一致,
# 而矩阵运算却要求维度不一致,但左行右列要一致,这是矩阵相乘的原理
import tensorflow as tf

w = tf.Variable([1,2,3], dtype=tf.float32)
x = tf.Variable([2,3,4], dtype=tf.float32)
b = tf.Variable([1,1,2], dtype=tf.float32)
c = tf.Variable([1,1,1], dtype=tf.float32)
d = tf.Variable([2,2,2], dtype=tf.float32)

wx = tf.multiply(w,x)  # 乘法
wxb  = tf.add(wx,b)  # 加法
wxbc = tf.subtract(wxb,c)  # 减法
wxbcd = tf.divide(wxbc,d)  # 除法

print('Out y tensor:%s'%(wxbcd))
print('Out y numpy value:{yV}'.format(yV=wxbcd.numpy()))

矩阵运算

###################################### 练习3 矩阵运算
# 计算 y = wx + b,其中
# x = [[1,2,3,4], 
#      [1,3,2,2],
#      [2,1,3,2]], w = [2,1,2,3] 列向量, b = [1,1,2] 列向量
# 计算 y = [None,None,None]
import tensorflow as tf

w = tf.Variable([[2],[1],[2],[3]], dtype=tf.float32)
x = tf.Variable([[1,2,3,4],[1,3,2,2],[2,1,3,2]], dtype=tf.float32)
b = tf.Variable([[1],[1],[2]], dtype=tf.float32)

wx = tf.matmul(x,w)  # 乘法
wxb  = tf.add(wx,b)  # 加法

print('Out wx  numpy value:\n%s'%(wx.numpy()))
#out:Out wx  numpy value:
#[[22.]
# [15.]
# [17.]]
print('Out wxb numpy value:\n{yV}'.format(yV=wxb.numpy()))
#out:Out wxb numpy value:
# [[23.]
#  [16.]
#  [19.]]

目标函数

### 线性回归目标函数 y = wx + b
import tensorflow as tf

class Model(object):
    def __init__(self):
        # 初始化变量
        self.W = tf.Variable(5.0)
        self.b = tf.Variable(0.0)
    
    def __call__(self, x):
        # x 只有一维数据情况
        return self.W * x + self.b
# 测试
model = Model()
print(model([2,5]))
#out:tf.Tensor([10. 25.], shape=(2,), dtype=float32)

损失函数

# 演示样式
def loss(predicted_y, true_y):
    return tf.reduce_mean(tf.square(predicted_y - true_y))

优化函数

def train(model, inputs, outputs, learning_rate):
    # 记录loss计算过程
    with tf.GradientTape() as t:
        loss_value = loss(model(inputs), outputs)
        # 对W,b求导
        dW, db = t.gradient(loss_value, [model.W, model.b])
        # 减去梯度×学习率
        model.W.assign_sub(dW*learning_rate)
        model.b.assign_sub(db*learning_rate)
发布了18 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41731978/article/details/103807214