深度学习模型数据预处理 主要包括如何reshape WEBSITE
我们将定义一个名为series_to_supervised()的新 Python函数,它采用单变量或多变量时间序列并将其构建为监督学习数据集。该函数有四个参数: data:作为列表或 2D NumPy 数组的观察序列。必需的。 n_in :作为输入 ( X )的滞后观察数。值可能在 [1…len(data)] 之间可选。默认为 1。 n_out:作为输出的观察数(y)。值可能在 [0…len(data)-1] 之间。可选的。默认为 1。 dropnan:布尔值是否删除具有 NaN 值的行。可选的。默认为真。 该函数返回一个值: return:用于监督学习的系列 Pandas DataFrame。
from pandas import DataFrame
from pandas import concat
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
"""
Frame a time series as a supervised learning dataset.
Arguments:
data: Sequence of observations as a list or NumPy array.
n_in: Number of lag observations as input (X).
n_out: Number of observations as output (y).
dropnan: Boolean whether or not to drop rows with NaN values.
Returns:
Pandas DataFrame of series framed for supervised learning.
"""
n_vars = 1 if type(data) is list else data.shape[1]
df = DataFrame(data)
cols, names = list(), list()
# input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
# forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
# put it all together
agg = concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
return agg
raw = DataFrame()
raw['ob1'] = [x for x in range(10)]
raw['ob2'] = [x for x in range(50, 60)]
values = raw.values
data = series_to_supervised(values, 1, 2)
print(data)
|