## 三、工程趋势

`target = a * time + b`

`target = a * time ** 2 + b * time + c`

## 四、示例 – 隧道流量

```from pathlib import Path
from warnings import simplefilter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
simplefilter("ignore")  # ignore warnings to clean up output cells
# Set Matplotlib defaults
plt.style.use("seaborn-whitegrid")
plt.rc("figure", autolayout=True, figsize=(11, 5))
plt.rc(
"axes",
labelweight="bold",
labelsize="large",
titleweight="bold",
titlesize=14,
)
plot_params = dict(
color="0.75",
,
markeredgecolor="0.25",
markerfacecolor="0.25",
legend=False,
)
%config InlineBackend.figure_format = 'retina'
data_dir = Path("../input/ts-course-data")
tunnel = pd.read_csv(data_dir / "tunnel.csv", parse_dates=["Day"])
tunnel = tunnel.set_index("Day").to_period()```

```moving_average = tunnel.rolling(
window=365,       # 365-day window
center=True,      # puts the average at the center of the window
min_periods=183,  # choose about half the window size
).mean()              # compute the mean (could also do median, std, min, max, ...)
ax = tunnel.plot(style=".", color="0.5")
moving_average.plot(
ax=ax, linewidth=3, title="Tunnel Traffic - 365-Day Moving Average", legend=False,
);```

```from statsmodels.tsa.deterministic import DeterministicProcess
dp = DeterministicProcess(
index=tunnel.index,  # dates from the training data
constant=True,       # dummy feature for the bias (y_intercept)
order=1,             # the time dummy (trend)
drop=True,           # drop terms if necessary to avoid collinearity
)
# `in_sample` creates features for the dates given in the `index` argument
X = dp.in_sample()

Dayconsttrend
2003-11-011.01.0
2003-11-021.02.0
2003-11-031.03.0
2003-11-041.04.0
2003-11-051.05.0

（顺便说一下，确定性过程是非随机或完全确定的时间序列的技术术语，就像 const 和趋势序列一样。从时间指数派生的特征通常是确定性的。）

```from sklearn.linear_model import LinearRegression
y = tunnel["NumVehicles"]  # the target
# The intercept is the same as the `const` feature from
# DeterministicProcess. LinearRegression behaves badly with duplicated
# features, so we need to be sure to exclude it here.
model = LinearRegression(fit_intercept=False)
model.fit(X, y)
y_pred = pd.Series(model.predict(X), index=X.index)```

```ax = tunnel.plot(style=".", color="0.5", title="Tunnel Traffic - Linear Trend")
_ = y_pred.plot(ax=ax, linewidth=3, label="Trend")```

```X = dp.out_of_sample(steps=30)
y_fore = pd.Series(model.predict(X), index=X.index)

```2005-11-17    114981.801146
2005-11-18    115004.298595
2005-11-19    115026.796045
2005-11-20    115049.293494
2005-11-21    115071.790944
Freq: D, dtype: float64```

```ax = tunnel["2005-05":].plot(title="Tunnel Traffic - Linear Trend Forecast", **plot_params)
ax = y_pred["2005-05":].plot(ax=ax, linewidth=3, label="Trend")
ax = y_fore.plot(ax=ax, linewidth=3, label="Trend Forecast", color="C3")
_ = ax.legend()```