tensorflow2.0学习笔记(一)

一、维度变换

import tensorflow as tf
a = tf.random.normal((4,3,2,1))
a.shape
TensorShape([4, 3, 2, 1])

转置

tf.transpose(a).shape
TensorShape([1, 2, 3, 4])

perm,设置转置维度,下面的例子是把第3和第4维度进行转置

tf.transpose(a,perm=[0,1,3,2]).shape
TensorShape([4, 3, 1, 2])

添加维度

a = tf.random.normal([4,35,8])

添加第0维度

tf.expand_dims(a,axis=0).shape
TensorShape([1, 4, 35, 8])

添加第3维度

tf.expand_dims(a,axis=3).shape
TensorShape([4, 35, 8, 1])

减少维度,只能减少shape=1的维度

tf.squeeze(tf.zeros([1,2,1,1,3])).shape
TensorShape([2, 3])
a = tf.zeros([1,2,1,3])
tf.squeeze(a,axis=0).shape
TensorShape([2, 1, 3])

二、广播

它根据维度自动对齐

x = tf.random.normal([4,32,32,3])
(x + tf.random.normal([3])).shape
TensorShape([4, 32, 32, 3])
(x + tf.random.normal([32,32,1])).shape
TensorShape([4, 32, 32, 3])
(x + tf.random.normal([4,1,1,1])).shape
TensorShape([4, 32, 32, 3])

广播例子,broadcast和tile的比较

a = tf.ones([3,4])
a.shape
TensorShape([3, 4])
a1 = tf.broadcast_to(a,[2,3,4])
a1.shape
TensorShape([2, 3, 4])
a2 = tf.expand_dims(a,axis=0)
a2.shape
TensorShape([1, 3, 4])
a3 = tf.tile(a2,[2,1,1])
a3.shape
TensorShape([2, 3, 4])

三、数学运算

两个张量之间的加减乘除

a = tf.ones([2,2])
b = tf.fill([2,2],2.)
tf.math.log(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[0., 0.],
       [0., 0.]], dtype=float32)>
tf.exp(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[2.7182817, 2.7182817],
       [2.7182817, 2.7182817]], dtype=float32)>

但这里是$\log_e , 没 有 其 他 比 如 ,没有其他比如 \log_2 , , \log_8 , 根 据 对 数 换 底 公 式 , ,根据对数换底公式, \frac{log_a b}{log_a c}=log_c b$,我们可以得出任意的对数

tf.math.log(8.)/tf.math.log(2.)
<tf.Tensor: shape=(), dtype=float32, numpy=3.0>

指数

tf.pow(b,3)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[8., 8.],
       [8., 8.]], dtype=float32)>
tf.pow(b,1/2)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1.4142135, 1.4142135],
       [1.4142135, 1.4142135]], dtype=float32)>

矩阵相乘(叉乘)

tf.matmul(a,b)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[4., 4.],
       [4., 4.]], dtype=float32)>

相乘和加的广播

x = tf.ones([4,2])
w = tf.ones([2,1])
b = tf.constant(0.1)
x @ w + b # @代表矩阵叉乘
<tf.Tensor: shape=(4, 1), dtype=float32, numpy=
array([[2.1],
       [2.1],
       [2.1],
       [2.1]], dtype=float32)>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值