【发布时间】: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 的每个位置与vel 的i-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_fn 和while_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