IBM Cloud Docs
惰性评估

惰性评估

惰性求值是一种将表达式求值延迟到需要其值时的求值策略。 将惰性求值策略与记忆技术相结合,可避免重复求值并显著缩短特定函数的运行时间。

时间序列库使用惰性求值来处理数据。 从理论上讲,将根据时间序列数据构造执行图(仅当具体化其输出时才会触发其求值)。 假定对象正在一维空间中移动,其位置由 x(t) 捕获。 您可以使用其速度 (v(t)) 和加速度 (a(t)) 时间序列来确定此对象的严苛加速/制动 (h(t)),如下所示:

# 1d location timeseries
x(t) = input location timeseries

# velocity - first derivative of x(t)
v(t) = x(t) - x(t-1)

# acceleration - second derivative of x(t)
a(t) = v(t) - v(t-1)

# harsh acceleration/braking using thresholds on acceleration
h(t) = +1 if a(t) > threshold_acceleration
     = -1 if a(t) < threshold_deceleration
     = 0 otherwise

这将生成以下形式的简单执行图:

x(t) --> v(t) --> a(t) --> h(t)

仅当执行操作 (例如 compute h(5...10),即 compute h(5), ..., h(10)) 时,才会触发求值。 该库会捕获时间序列之间的窄时间依赖关系。 在此示例中,h(5...10) 需要 a(5...10),而后者又需要 v(4...10),而后者则需要 x(3...10)。 仅评估 a(t)v(t)x(t) 的相关部分。

h(5...10) <-- a(5...10) <-- v(4...10) <-- x(3...10)

此外,还会对评估进行记忆,因此可以在 h 上的后续操作中复用这些评估。 例如,当针对 h(7...12) 的请求跟在针对 h(5...10) 的请求之后时,将利用回忆录值 h(7...10) ; 此外,将使用 a(11...12), v(10...12)x(9...12)h(11...12) 进行求值,这将反过来利用先前计算中的 v(10)x(9...10) 回忆录。

在更常见的示例中,您可以定义平滑的速率时间序列,如下所示:

# 1d location timeseries
x(t) = input location timeseries

# velocity - first derivative of x(t)
v(t) = x(t) - x(t-1)

# smoothened velocity
# alpha is the smoothing factor
# n is a smoothing history
v_smooth(t) =  (v(t)*1.0 + v(t-1)*alpha + ... + v(t-n)*alpha^n) / (1 + alpha + ... + alpha^n)

# acceleration - second derivative of x(t)
a(t) = v_smooth(t) - v_smooth(t-1)

在此示例中,h(l...u) 具有以下时间依赖关系。 对 h(l...u) 的评估将严格遵守此时间依赖关系并进行记忆。

h(l...u) <-- a(l...u) <-- v_smooth(l-1...u) <-- v(l-n-1...u) <-- x(l-n-2...u)

示例

以下示例显示了 Python 代码片段,此片段对简单的内存中时间序列实施剧烈加速。 此库包含多个内置变换。 在此示例中,将差异变换应用于位置时间序列两次以计算加速度时间序列。 映射操作将使用在代码样本之后定义的苛刻 lambda 函数应用于加速时间序列,该函数将加速映射到 +1 (苛刻加速),-1 (苛刻制动) 和 0 (否则)。 过滤操作仅选择观察到剧烈加速或剧烈减速的实例。 在调用 get_values 之前,将创建执行图,但不会执行任何计算。 在调用 get_values(5, 10) 时,将通过对执行图中可能最窄的时间依赖关系进行记忆化来执行求值。

import sparktspy as tspy
from tspy.functions import transformers

x = tspy.time_series([1.0, 2.0, 4.0, 7.0, 11.0, 16.0, 22.0, 29.0, 28.0, 30.0, 29.0, 30.0, 30.0])
v = x.transform(transformers.difference())
a = v.transform(transformers.difference())
h = a.map(harsh).filter(lambda h: h != 0)

print(h[5, 10])

如下所示定义 harsh lambda:

def harsh(a):
    threshold_acceleration = 2.0
    threshold_braking = -2.0

    if (a > threshold_acceleration):
        return +1
    elif (a < threshold_braking):
        return -1
    else:
        return 0

了解更多

要使用 tspy Python SDK,请参阅 tspy Python SDK 文档