03_基础的Tensor OP

1.矩阵乘法和向量乘法

要分清楚自己要的是向量乘法还是矩阵乘法。

  • 矩阵乘法:tf.matmul()
  • 向量乘法:tf.Tensor * tf.Tensor
# 矩阵乘法:
c = tf.matmul(a,b)
print(c.numpy())

'''
[[1 2]
 [1 2]]
'''

# 向量乘法:
d = a*b
print(d.numpy())

'''
[[1 0]
 [0 2]]
'''

2.均值和方差

  • 均值:tf.reduce_mean()
  • 方差:tf.math.squared_difference()
# 均值
m = [1,2,3,4,5]
mean = tf.reduce_mean(m)
print(mean)

'''
tf.Tensor(3, shape=(), dtype=int32)
'''

# 方差
x = [1,3,5,7,9]
y = [1,1,1,1,1]
r = tf.math.squared_difference(x,y)
print(r)

'''
tf.Tensor([ 0  4 16 36 64], shape=(5,), dtype=int32)
'''

3.随机数生成

  • 正态分布:tf.random.normal()
  • 均匀分布:tf.random.uniform()
# 正态分布
rand1 = tf.random.normal(shape=(3,2),mean=0.0,stddev=2.0)
print(rand1)
print("\n")

'''
tf.Tensor(
[[-0.9260874  4.9333167]
 [-2.0966494  2.6556277]
 [ 1.8420827  1.7115388]], shape=(3, 2), dtype=float32)
'''

# 均匀分布
rand2 = tf.random.uniform(shape=(2,4),minval=1,maxval=10)
print(rand2)
print("\n")

'''
tf.Tensor(
[[4.1472673 1.3256727 5.5261173 1.2175164]
 [7.5022736 6.664027  7.76919   7.363538 ]], shape=(2, 4), dtype=float32)
'''

4.寻找极值

  • 极大值:tf.argmax()
  • 极小值:tf.argmin()

返回要寻找值的索引,也是一个Tensor

a = [1,3,5,2,11,0,99]
# 极大值
d = tf.argmax(a)
print(d)
# 极小值
e = tf.argmin(a)
print(e)

'''
tf.Tensor(6, shape=(), dtype=int64)
tf.Tensor(5, shape=(), dtype=int64)
'''

本部分完整代码:
02_basic_op.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值