[英]Numpy-like indexing and assignment with Tensorflow
I made a simple example of numpy array indexing and assignment where the goal is to make a small white square on a black screen.我做了一个简单的 numpy 数组索引和分配示例,目标是在黑屏上制作一个白色的小方块。 How would I replicate the following code using Tensorflow?
我将如何使用 Tensorflow 复制以下代码?
black_img = np.zeros([5, 5, 3])
white_rect = np.ones([3, 3])
size = np.arange(3)
black_img[size, size] = white_rect
You can create constants or variables in TensorFlow.您可以在 TensorFlow 中创建常量或变量。
black_img = np.zeros([5, 5, 3], dtype = np.int32)
black_img_tf = tf.constant(np.zeros([5, 5, 3], dtype = np.int32))
Output:输出:
<tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]])>
However, TensorFlow does not support item assignment like NumPy.但是,TensorFlow 不支持像 NumPy 那样的项目分配。 However, you can create a new constant or variable using results obtained from NumPy operations.
但是,您可以使用从 NumPy 操作获得的结果创建新的常量或变量。
Code:代码:
black_img[size, size] = white_rect
tf.constant(black_img)
Output:输出:
<tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
array([[[1, 1, 1],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]])>
Note that individual item assignment is not allowed but you can do operations like addition, subtraction on tensors.请注意,不允许单个项目分配,但您可以对张量进行加法、减法等操作。
c = tf.constant(np.ones([3, 3], dtype = np.int32)) + tf.constant(np.ones([3, 3], dtype = np.int32))
c
Output:输出:
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[2, 2, 2],
[2, 2, 2],
[2, 2, 2]])>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.