【问题标题】:Tensorflow: sum/product an array to specific elements in a tensorTensorflow:将数组与张量中的特定元素相加/乘积
【发布时间】:2017-08-04 09:35:16
【问题描述】:

您好,我有一个稀疏格式的浮点 [时间,位置] 坐标数组,例如

times = [0.1, 0.1, 1.5, 1.9, 1.9, 1.9]
posit = [2.1, 3.5, 0.4, 1.3, 2.7, 3.5]

以及一系列速度,例如

vel = [0.5,0.7,1.0]

我必须将i-th 的每个位置与veli-th 元素相乘。

在 numpy 中使用 for 非常简单:

import numpy

times = numpy.array([0.1, 0.1, 1.5, 1.9, 1.9, 1.9])
posit = numpy.array([2.1, 3.5, 0.4, 1.3, 2.7, 3.5])

vel = numpy.array([0.5,0.7,1.0])

uniqueTimes = numpy.unique(times, return_index=True)
uniqueIndices = uniqueTimes[1]
uniqueTimes = uniqueTimes[0]

numIndices = numpy.size(uniqueTimes)-1
iterator = numpy.arange(numIndices)+1
for i in iterator:
    posit[uniqueIndices[i-1]:uniqueIndices[i]] = posit[uniqueIndices[i-1]:uniqueIndices[i]]*vel[i-1]

在张量流中,我可以收集我需要的所有信息

import tensorflow as tf

times = tf.constant([0.1, 0.1, 1.5, 1.9, 1.9, 1.9])
posit = tf.constant([2.1, 3.5, 0.4, 1.3, 2.7, 3.5])

vel = tf.constant([0.5,0.7,1.0])   

uniqueTimes, uniqueIndices, counts = tf.unique_with_counts(times)
uniqueIndices = tf.cumsum(tf.pad(tf.unique_with_counts(uniqueIndices)[2],[[1,0]]))[:-1]

但我不知道如何做这个产品。使用int 元素我可以使用稀疏到密集的张量并使用tf.matmul,但使用float 我不能。 此外,循环很困难,因为map_fnwhile_loop 要求每个“行”的大小相同,但我每次都有不同数量的位置。出于同样的原因,我不能每次都单独工作并用tf.concat 更新最终的positions 张量。有什么帮助吗?也许使用scatter_update 或变量赋值?


根据 vijai m 的回答,我发现 numpy 和 tensorflow 代码之间的差异高达 1.5%。您可以使用这些数据进行检查

times [0.1,  0.1, 0.2, 0.2]
posit [58.98962402,  58.9921875, 60.00390625, 60.00878906]
vel [0.99705114,0.99974157]

他们回来了

np: [ 58.81567188  58.8182278   60.00390625  60.00878906]
tf: [ 58.81567001  58.81822586  59.98839951  59.9932785 ]
differences: [  1.86388465e-06   1.93737304e-06   1.55067444e-02   1.55105566e-02]

【问题讨论】:

  • 你能修复 numpy 代码并打印你想要的输出吗?
  • 很抱歉,复制粘贴错误:(已编辑
  • 手动计算,结果的最后一个值是60.00878906*0.99974157 = 59.9932785?
  • 是的,我现在注意到当vel 接近1 时,numpy 返回与posit 相同的值。

标签: python tensorflow


【解决方案1】:

您的 numpy 代码不起作用。我希望这是您正在寻找的:

uniqueTimes, uniqueIndices, counts = tf.unique_with_counts(times)
out = tf.gather_nd(vel,uniqueIndices[:,None])*posit

【讨论】:

  • 非常感谢。您的答案有效,但是使用我的数据,即使在 float64 中,它也会返回与 numpy 代码相差高达 1.5% 的值,这对于我的目的来说是相当多的。我试图理解为什么。
  • 与手动计算相比,上面的 numpy 代码给出了错误的值,你能发布给出 1.5% 差异的 numpy 示例吗?。
  • 你确定吗?我刚刚检查过,numpy 代码给我的值与手动计算完全相同:[ 1.05 1.75 0.28 1.3 2.7 3.5 ],你有相同的值吗?
  • 无论如何,我用可用于检查我的结果的数据编辑了问题。再次感谢您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多