如何使用 Lambda 层规范化数据?

How to normalize data using Lambda layer?

我将 x 列表设为

x = list(np.arange(10))

min = np.min(x)

max = np.max(x)

我可以使用以下方法创建窗口数据集:

def get_windowed_data(series,window_size):

  dt = tf.data.Dataset.from_tensor_slices(series)
  dt = dt.window(window_size, shift = 1,drop_remainder = True)
  dt = dt.flat_map(lambda window: window.batch(window_size)) # make each window a batch
  dt = dt.map(lambda window: (window[:-1],window[-1:])) # consider the last element as label and the rest as window
  return dt

这给了我输出结果。因此,每一行包含一个元组,其中第一个元素是一个包含多个元素的列表,第二个元素是一个包含单个元素的列表。

[0 1 2 3]   [4]
[1 2 3 4]   [5]
[2 3 4 5]   [6]
[3 4 5 6]   [7]
[4 5 6 7]   [8]
[5 6 7 8]   [9]

现在我希望仅对第一个元素中的数据进行规范化(在 0 和 1 之间),并像以前一样保留标签并尝试了以下代码:

def get_windowed_data(series,window_size,min,max):

  dt = tf.data.Dataset.from_tensor_slices(series)
  dt = dt.window(window_size, shift = 1,drop_remainder = True)
  #dt = dt.flat_map(lambda window: window.batch(window_size)) # make each window a batch
  dt = dt.flat_map(lambda window: ([ (x-min)/max for x in window[:-1].numpy()],window[-1:])) 
  return dt
  

所以,例如前两行的输出应该是:

[0.0, 0.1111111111111111, 0.2222222222222222, 0.3333333333333333] [4]
[0.1111111111111111, 0.2222222222222222, 0.3333333333333333, 0.4444444444444444]      [5]

但是,使用我的代码它会抱怨:

   lambda window: ([ (x-min)/max for x in window[:-1].numpy()],window[-1:]))

    TypeError: '_VariantDataset' object is not subscriptable

拆分成两个元素后,可以使用另一个map函数:

ds = ds.map(lambda wx, wy: ((wx - min) / max, wy))

wx是window,wy是这里的目标。完整的示例如下所示:

import tensorflow as tf
import numpy as np

x = list(np.arange(10))

min = np.min(x)
max = np.max(x)


def get_windowed_data(series, window_size, min_value, max_value):
    ds = tf.data.Dataset.from_tensor_slices(series)
    ds = ds.window(window_size, shift=1, drop_remainder=True)
    ds = ds.flat_map(lambda w: w.batch(window_size))
    ds = ds.map(lambda w: (w[:-1], w[-1:]))
    ds = ds.map(lambda wx, wy: ((wx - min_value) / max_value, wy))
    return ds


data_normalized = get_windowed_data(x, 5, min, max)

for x, y in data_normalized:
    print(x.numpy(), y.numpy())

这将打印:

[0.         0.11111111 0.22222222 0.33333333] [4]
[0.11111111 0.22222222 0.33333333 0.44444444] [5]
[0.22222222 0.33333333 0.44444444 0.55555556] [6]
[0.33333333 0.44444444 0.55555556 0.66666667] [7]
[0.44444444 0.55555556 0.66666667 0.77777778] [8]
[0.55555556 0.66666667 0.77777778 0.88888889] [9]