深度学习(17)TensorFlow高阶操作六: 高阶OP
深度學習(17)TensorFlow高階操作六: 高階OP
- 1. Where(tensor)
- 2. where(cond, A, B)
- 3. 1-D scatter_nd
- 4. 2-D scatter_nd
- 5. meshgrid
- (1) Points(點的范圍)
- (2) Numpy
- (3) GPU acceleration
- (4) 還原
- (5) 應用
- 6. meshgrid應用實例
Outline
- where
- scatter_nd
- meshgrid
1. Where(tensor)
where只有一個參數tensor的時候,會返回這個tensor中所有值為True的坐標。
(1) mask=a>0: 將a中大于0的元素標位True,小于0的元素標為False,最后形成一個mask;
(2) tf.boolean_mask(a, mask): 將a按照mask來篩選出大于0的元素;
(3) indices = tf.where(mask): 利用where()函數將mask中值為True的坐標拿出來;
(4) tf.gather_nd(a, indices): 利用gather_nd()函數將a按照indices取出元素;
2. where(cond, A, B)
如果where()中有3個參數,那么就會根據True/False以及A和B來構建新的Tensor;
(1) tf.where(mask, A, B): 根據mask中True和False的分布來構建新的Tensor,其中,True的值對應A中的元素值1,False的值對應B中的元素值0。
3. 1-D scatter_nd
根據坐標進行有目的性地更新
- tf.scatter_nd(
- indices,
- updates,
- shape
其中,shape為模板,updates里放的是坐標,output是結合了shape和updates的坐標;
(1) tf.scatter_nd(indices, updates, shape): 將indices和updates對應后放入到shape中,即: 第5個元素放入9,第4個元素放入10,第2個元素放入11,第8個元素放入12。
4. 2-D scatter_nd
(1) tf.scatter_nd(indices, updates, shape): 將indices和updates的元素對應后放入到shape中;
5. meshgrid
在3-D圖像上利用坐標將函數畫出來。
(1) Points(點的范圍)
- [y, x, 2]
- [5, 5, 2]
- [N, 2]
如上圖所示,一共有25個點,每個點由2個坐標(x和y)來表示,這樣其shape=[25, 2];
(2) Numpy
其中y為[-2, 2]間隔5個點; x為[-2, 2]間隔5個點; 再將這些點保存到points=[]里;
這個方法是利用Numpy來實現的,沒有經過GPU加速,而且無法與TensorFlow深度結合在一起。
(3) GPU acceleration
- x: [-2~2]
- y: [-2~2]
→\to→ - Points: [N, 2]
y = tf.linspace(-2., 2, 5): 給出y的范圍,即[-2., -1., 0., 1., 2.];
x = tf.linspace(-2., 2, 5): 給出x的范圍,即[-2., -1., 0., 1., 2.];
points_x, points_y = tf.meshgrid(x, y): 將坐標(x, y)中的x和y拆開分別保存到兩個Tensor中去,即points_x和points_y;
(4) 還原
Points: [N, 2]
points = tf.stack([points_x, points_y], axis=2): 利用stack()函數進行第3個維度的合并;
(5) 應用
例如,我們需要畫出如下函數的曲線或者等高線。
z=sin?(x)+sin?(y)z=sin?(x)+sin?(y)z=sin?(x)+sin?(y)
6. meshgrid應用實例
import tensorflow as tf import matplotlib.pyplot as pltdef func(x):""":param x: [b, 2]:return: z"""z = tf.math.sin(x[..., 0]) + tf.math.sin(x[..., 1])return zx = tf.linspace(0., 2*3.14, 500) y = tf.linspace(0., 2*3.14, 500) # [50, 50] point_x, point_y = tf.meshgrid(x, y) # [50, 50, 2] points = tf.stack([point_x, point_y], axis=2) # points = tf.reshape(points, [-1, -2]) print('points:', points.shape) z = func(points) print('z:', z.shape)plt.figure('plot 2d func value') plt.imshow(z, origin='lower', interpolation='none') plt.colorbar()plt.figure('plot 2d func contour') plt.contour(point_x, point_y, z) plt.colorbar() plt.show()運行結果如下:
參考文獻:
[1] 龍良曲:《深度學習與TensorFlow2入門實戰》
[2] https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/scatter_nd
總結
以上是生活随笔為你收集整理的深度学习(17)TensorFlow高阶操作六: 高阶OP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 未成年能不能去办银行卡 未成年可不可以办
- 下一篇: 深度学习(18)神经网络与全连接层一: