Tensorflow 张量运算2:数据收集

1. tf.gather

import tensorflow as tf 
# tf.gather适合索引没有规则的场合
# 以班级成绩册为例,共有4个班,每班35个同学,8门成绩
x = tf.random.uniform([4,35,8],minval=0,maxval=100,dtype=tf.int32)

# 收集第1,2班级的成绩册
tf.gather(x,[0,1],axis=0)

# 收集所有班级第1,4,18,32号同学的成绩
tf.gather(x,[0,3,17,31],axis=1)

# 收集所有同学第3,5科的成绩
tf.gather(x,[2,4],axis=2)

# 收集第2,3班级的第3,6.18号同学的5,8科目成绩,通过多个tf.gather组合实现
x1 = tf.gather(x,[1,2],axis=0)
x2 = tf.gather(x1,[2,5,17],axis=1)
x3 = tf.gather(x2,[4,7],axis=2)

2. tf.gather_nd

import tensorflow as tf 
# tf.gather_nd通过指定每次采样的座标实现采样多个点的目的
# 以班级成绩册为例,共有4个班,每班35个同学,8门成绩
x = tf.random.uniform([4,35,8],minval=0,maxval=100,dtype=tf.int32)

# 收集第2个班级第3个同学的所有科目,第3个班级第4同学的成绩,第4个班级的第5个同学的成绩
tf.gather_nd(x,[[1,2],[2,3],[3,4]])

# 收集第2个班级第3个同学的第5科目,第3个班级第4同学的第5科目成绩,第4个班级的第5个同学的第5科目成绩
tf.gather_nd(x,[[1,2,4],[2,3,4],[3,4,4]])

3.tf.meshgrid

import tensorflow as tf 
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# tf.meshgrid生成网格坐标
x = tf.linspace(-8.,8.,5) #设置x坐标的间隔
'''输出
[-8. -4.  0.  4.  8.]'''

print(x.numpy())
y = tf.linspace(-8.,8.,3) #设置y坐标的间隔
'''输出
[-8.  0.  8.]'''
x,y = tf.meshgrid(x,y)
'''输出
[[-8. -4.  0.  4.  8.]
 [-8. -4.  0.  4.  8.]
 [-8. -4.  0.  4.  8.]]
[[-8. -8. -8. -8. -8.]
 [ 0.  0.  0.  0.  0.]
 [ 8.  8.  8.  8.  8.]]
'''

z = x**2+y**2
'''输出
[[128.  80.  64.  80. 128.]
 [ 64.  16.   0.  16.  64.]
 [128.  80.  64.  80. 128.]]
'''

fig = plt.figure()
ax = Axes3D(fig)

ax.contour3D(x.numpy(), y.numpy(), z.numpy(), 50)
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪易

给我来点鼓励吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值