美文网首页
TensorFlow高阶操作之补充

TensorFlow高阶操作之补充

作者: 酵母小木 | 来源:发表于2020-02-04 20:17 被阅读0次

【碎碎念】不知道今天能不能完成任务了,看完8节网课是基本操作,但是到目前为止,只看了3节网课。

1.【tf.where()】

//返回当前Tensor中True元素所在的坐标
tf.where(
    condition,
    x=None,
    y=None,
    name=None
)

condition: A Tensor of type bool
x: A Tensor which is of the same type as y, and may be broadcastable with condition and y.
y: A Tensor which is of the same type as x, and may be broadcastable with condition and x.
当X\Y存在时,当mask对应位置为True时,从A中选取元素,若为False时,从B中选取元素

//获取元素中满足条件的值
In [5]: a = tf.random.normal([3, 3])
Out[6]: <tf.Tensor: id=8, shape=(3, 3), dtype=float32, numpy=
array([[-0.39900583,  1.4840462 ,  1.2204064 ],
       [-1.0376796 , -0.8071848 ,  0.38709766],
       [-0.14686483, -0.28148735,  0.34916955]], dtype=float32)>

//获得数据的mask
In [7]: mask = a > 0
Out[8]: <tf.Tensor: id=10, shape=(3, 3), dtype=bool, numpy=
array([[False,  True,  True],
       [False, False,  True],
       [False, False,  True]])>
=================================================
//通过tf.boolean_mask获取为True的元素
In [9]: tf.boolean_mask(a, mask)
Out[9]: <tf.Tensor: id=37, shape=(4,), dtype=float32, numpy=array([1.4840462 , 1.2204064 , 0.38709766, 0.34916955], dtype=float32)>
==========================================================
//获取为True的元素索引
In [10]: indices = tf.where(mask)
Out[11]: <tf.Tensor: id=38, shape=(4, 2), dtype=int64, numpy=
array([[0, 1],
       [0, 2],
       [1, 2],
       [2, 2]], dtype=int64)>
//通过索引得到满足条件的元素
In [12]: tf.gather_nd(a, indices)
Out[12]: <tf.Tensor: id=39, shape=(4,), dtype=float32, numpy=array([1.4840462 , 1.2204064 , 0.38709766, 0.34916955], dtype=float32)>
==========================================================
//where的另外一种用法
In [14]: mask
Out[14]: <tf.Tensor: id=10, shape=(3, 3), dtype=bool, numpy=
array([[False,  True,  True],
       [False, False,  True],
       [False, False,  True]])>

In [15]: A = tf.fill([3, 3], 2)
Out[16]: <tf.Tensor: id=42, shape=(3, 3), dtype=int32, numpy=
array([[2, 2, 2],
       [2, 2, 2],
       [2, 2, 2]])>

In [17]: B = tf.fill([3, 3], -2)
Out[18]: <tf.Tensor: id=45, shape=(3, 3), dtype=int32, numpy=
array([[-2, -2, -2],
       [-2, -2, -2],
       [-2, -2, -2]])>

In [19]: tf.where(mask, A, B)
Out[19]: <tf.Tensor: id=46, shape=(3, 3), dtype=int32, numpy=
array([[-2,  2,  2],
       [-2, -2,  2],
       [-2, -2,  2]])>

2.【tf.scatter_nd()】

//通过坐标有目的性的更新
tf.scatter_nd(
    indices,      //填充位置索引
    updates,    //填充值
    shape,      //全零底板
    name=None
)

indices: A Tensor. Must be one of the following types: int32, int64. Index tensor.
updates: A Tensor. Updates to scatter into output.
shape: A Tensor. Must have the same type as indices. 1-D. The shape of the resulting tensor.

In [20]: indices = tf.constant([[4], [3], [1], [7]])

In [21]: updates = tf.constant([9, 10, 11, 12])

In [22]: shape = tf.constant([8])

In [23]: shape
Out[23]: <tf.Tensor: id=49, shape=(1,), dtype=int32, numpy=array([8])>

In [24]: tf.scatter_nd(indices, updates, shape)
Out[24]: <tf.Tensor: id=50, shape=(8,), dtype=int32, numpy=array([ 0, 11,  0, 10,  9,  0,  0, 12])>
//如果需要对Tensor的指定位置进行更新,则需要两步
- 【清零】将指定位置元素取出后更新到底板上,相减
- 【更新】更新元素更新到底板上,相加

============================================================
//三维上的使用
In [26]: indices = tf.constant([[0], [2]])
In [28]: updates = tf.constant([  [[5, 5, 5, 5], [6, 6, 6, 6],
    ...:                             [7, 7, 7, 7], [8, 8, 8, 8]],
    ...:
    ...:                             [[5, 5, 5, 5], [6, 6, 6, 6],
    ...:                              [7, 7, 7, 7], [8, 8, 8, 8]]])

In [29]: updates.shape
Out[29]: TensorShape([2, 4, 4])

In [32]: shape = tf.constant([4, 4, 4])

In [33]: tf.scatter_nd(indices, updates, shape)
Out[33]: <tf.Tensor: id=57, shape=(4, 4, 4), dtype=int32, numpy=
array([[[5, 5, 5, 5],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [8, 8, 8, 8]],

       [[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]],

       [[5, 5, 5, 5],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [8, 8, 8, 8]],

       [[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]]])>

3.【tf.scatter_nd()】

//通过范围,生成坐标点的坐标网格
tf.meshgrid(
    *args,
    **kwargs
)

*args: Tensors with rank 1.
**kwargs: - indexing: Either 'xy' or 'ij' (optional, default: 'xy').

//使用numpy选取25组点
points = []
for y in np.linspace(-2, 2, 5):
  for x in np.linspace(-2, 2, 5):
    points.append([x, y])
return np.array(points)
===========================================================
//使用tensorflow实现
In [34]: y = tf.linspace(-2., 2, 5)
Out[35]: <tf.Tensor: id=61, shape=(5,), dtype=float32, numpy=array([-2., -1.,  0.,  1.,  2.], dtype=float32)>

In [36]: x = tf.linspace(-2., 2, 5)

//points为两个【5,5】的Tensor
In [37]: points = tf.meshgrid(x, y)
Out[38]:
[<tf.Tensor: id=83, shape=(5, 5), dtype=float32, numpy=
 array([[-2., -1.,  0.,  1.,  2.],
        [-2., -1.,  0.,  1.,  2.],
        [-2., -1.,  0.,  1.,  2.],
        [-2., -1.,  0.,  1.,  2.],
        [-2., -1.,  0.,  1.,  2.]], dtype=float32)>,
 <tf.Tensor: id=84, shape=(5, 5), dtype=float32, numpy=
 array([[-2., -2., -2., -2., -2.],
        [-1., -1., -1., -1., -1.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.,  2.]], dtype=float32)>]

//points[0]为Y
In [39]: points[0]
Out[39]: <tf.Tensor: id=83, shape=(5, 5), dtype=float32, numpy=
array([[-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.]], dtype=float32)>

//points[1]为X
In [40]: points[1]
Out[40]: <tf.Tensor: id=84, shape=(5, 5), dtype=float32, numpy=
array([[-2., -2., -2., -2., -2.],
       [-1., -1., -1., -1., -1.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.,  2.]], dtype=float32)>

//通过tf.stack()将两组数据进行合并成坐标, points为【5,5,2】
In [42]: points = tf.stack([points[1], points[0]], axis=2)

In [43]: points
Out[43]: <tf.Tensor: id=85, shape=(5, 5, 2), dtype=float32, numpy=
array([[[-2., -2.],
        [-2., -1.],
        [-2.,  0.],
        [-2.,  1.],
        [-2.,  2.]],

      ........................

       [[ 2., -2.],
        [ 2., -1.],
        [ 2.,  0.],
        [ 2.,  1.],
        [ 2.,  2.]]], dtype=float32)>

使用meshgrid()绘制z = sin(x) + sin(y)的等高线

import tensorflow as tf

import matplotlib.pyplot as plt

def func(x):
    """

    :param x: [b, 2]
    :return:
    """
    z = tf.math.sin(x[...,0]) + tf.math.sin(x[...,1])

    return z


x = 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()

参考资料

相关文章

网友评论

      本文标题:TensorFlow高阶操作之补充

      本文链接:https://www.haomeiwen.com/subject/fmldxhtx.html