numpy - 在 Tensorflow 中进行基于切片的乘法的最有效方法

标签 numpy tensorflow slice

我正在尝试执行将二维矩阵的切片乘以常数的运算。

例如,如果我想将除前两列之外的所有内容相乘

要在 numpy 中执行此操作,可以这样做:

a = np.array([[0,7,4],
              [1,6,4],
              [0,2,4],
              [4,2,7]])
a[:, 2:] = 2.0*a[:, 2:]

>> a
>> array([[ 0,  7,  8],
          [ 1,  6,  8],
          [ 0,  2,  8],
          [ 4,  2, 14]])

但是,至少从我的搜索来看,tensorflow 目前没有直接的方法来做到这一点。

我当前的解决方案是创建 a 最初作为两个单独的张量 a1 和 a2,将第二个张量乘以 2.0,然后将它们跨 axis=1 连接起来。操作非常简单,这是可能的。不过我有两个问题

  1. 这是最有效的方法吗
  2. 是否有更好的(通用/高效)方法来执行此操作,以使功能更接近 numpy 的切片魔法(也许 https://www.tensorflow.org/api_docs/python/tf/scatter_

最佳答案

一种选择是执行逐项乘法,如下所示:

import tensorflow as tf

a = tf.Variable(initial_value=[[0,7,4],[1,6,4],[0,2,4],[4,2,7]])
b = tf.mul(a,[1,1,2])

s=tf.InteractiveSession()
s.run(tf.global_variables_initializer())
b.eval()

这会打印

array([[ 0,  7,  8],
       [ 1,  6,  8],
       [ 0,  2,  8],
       [ 4,  2, 14]])

更一般地说,如果 a 有更多列,您可以执行类似的操作:

import tensorflow as tf

a = tf.Variable(initial_value=[[0,7,4],[1,6,4],[0,2,4],[4,2,7]])
b = tf.mul(a,[1,1]+[2 for i in range(a.get_shape()[1]-2)])

s=tf.InteractiveSession()
s.run(tf.global_variables_initializer())
b.eval()

或者,如果您的矩阵有很多列,您可以替换

b = tf.mul(a,[1,1]+[2 for i in range(a.get_shape()[1]-2)])

import numpy as np
b = tf.mul(a,np.concatenate((np.array([1,1]),2*np.ones(a.get_shape()[1]-2))))

关于numpy - 在 Tensorflow 中进行基于切片的乘法的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480656/

相关文章:

python - 列表的哪些元素进入哪个直方图箱?

python - 如何更改每一行中特定单元格左侧的所有值

python - TF 对象检测 : int() argument must be a string, 类似字节的对象或数字,而不是 'NoneType'

python - 根据另一列中的值更新特定列中的值

python - 使用字符串定义 Numpy 数组切片

slice - Frama-C 中的条件切片

python - 将函数应用于 pandas 列

python - 绘制分段拟合非线性数据

python - 警告 :tensorflow :`write_grads` will be ignored in TensorFlow 2. 0 为 `TensorBoard` 回调

tensorflow - 何时停止训练对象检测 tensorflow