Python 用偏移量添加张量

Python 用偏移量添加张量,python,tensorflow,Python,Tensorflow,例如, 我有一个二维张量 array = np.array([1,2,3],[1,2,3],[1,2,3]) tensor = tf.constant(array) 我想计算张量中每一列的总和,但要求每一行与其他行相偏移 [0,1,2,3,0,0] [0,0,1,2,3,0] [0,0,0,1,2,3] 是否可以有效地执行此类计算?我尝试使用SparseTensor和tf在稀疏表示上计算总和。sparse\u reduce\u sum但发现它对我的数据大小计算效率低下。您可以手动构建移位总和

例如, 我有一个二维张量

array = np.array([1,2,3],[1,2,3],[1,2,3])
tensor = tf.constant(array)
我想计算张量中每一列的总和,但要求每一行与其他行相偏移

[0,1,2,3,0,0]
[0,0,1,2,3,0]
[0,0,0,1,2,3]

是否可以有效地执行此类计算?我尝试使用
SparseTensor
tf在稀疏表示上计算总和。sparse\u reduce\u sum
但发现它对我的数据大小计算效率低下。

您可以手动构建移位总和图:

import tensorflow as tf
import numpy as np

array1 = np.array([[1., 2., 3.],
                  [1., 2., 3.],
                  [1., 2., 3.]], dtype=np.float32)
tensor1 = tf.Variable(tf.constant(array1))

array2 = np.array([[1., 2., 3., 4.],
                  [1., 2., 3., 4.],
                  [1., 2., 3., 4.],
                  [1., 2., 3., 4.]], dtype=np.float32)
tensor2 = tf.Variable(tf.constant(array2))

def shifted_sum(tensor):
  def shifted_sum_one_column(i):
    s = tf.constant(0., dtype=tf.float32)
    for j in range(tensor.get_shape()[0]):
      if 0 <= i - (j + 1) < tensor.get_shape()[1]:
        s += tensor[tf.constant(j, dtype=tf.int32),
                    tf.constant(i - (j + 1), dtype=tf.int32)]
    return s

  result = []

  for i in range(tensor.get_shape()[1] + tensor.get_shape()[0]):
    result.append(shifted_sum_one_column(i))

  result = tf.stack(result)
  return result

shifted_tensor_1 = shifted_sum(tensor1)
shifted_tensor_2 = shifted_sum(tensor2)

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  print(sess.run(shifted_tensor_1))
  print(sess.run(shifted_tensor_2))
将tensorflow导入为tf
将numpy作为np导入
array1=np.array([[1,2,3.],
[1., 2., 3.],
[1,2,3.]],dtype=np.32)
张量1=tf.变量(tf.常数(数组1))
array2=np.数组([[1,2,3,4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1,2,3,4.],dtype=np.32)
张量2=tf.变量(tf.常数(array2))
定义移位和(张量):
def移位和一列(i):
s=tf.constant(0,dtype=tf.float32)
对于范围内的j(张量get_shape()[0]):

如果0 hm…如果
tf.diag\u部分
支持
offset
参数,如
numpy.diagonal