Python Fourier Features: Generate Time Series Features for Machine Learning
import numpy as np
import pandas as pd
def fourier_features(index, freq, order):
time = np.arange(len(index), dtype=np.float32)
k = 2 * np.pi * (1 / freq) * time
features = {}
for i in range(1, order + 1):
features.update({
f'sin_{freq}_{i}': np.sin(i * k),
f'cos_{freq}_{i}': np.cos(i * k),
})
return pd.DataFrame(features, index=index)
# Compute Fourier features to the 4th order (8 new features) for a
# series y with daily observations and annual seasonality:
#
# fourier_features(y, freq=365.25, order=4)
# Input example
index = np.arange(365)
y = np.sin(2*np.pi*index/365) + np.random.normal(0, 0.1, size=365)
# Output example
print(fourier_features(index, freq=365.25, order=4))
Input:
index = np.arange(365)
y = np.sin(2*np.pi*index/365) + np.random.normal(0, 0.1, size=365)
Output:
sin_365.25_1 cos_365.25_1 sin_365.25_2 cos_365.25_2 sin_365.25_3 cos_365.25_3 sin_365.25_4 cos_365.25_4
0.0 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000
1.0 0.017213 0.999852 0.034422 0.999407 0.051634 0.998667 0.068844 0.997632
2.0 0.034422 0.999407 0.068844 0.997632 0.103255 0.994662 0.137667 0.990479
3.0 0.051634 0.998667 0.103255 0.994662 0.154867 0.987688 0.206481 0.978465
4.0 0.068844 0.997632 0.137667 0.990479 0.206481 0.978465 0.275293 0.961702
...
360.0 -0.051634 0.998667 -0.103255 0.994662 -0.154867 0.987688 -0.206481 0.978465
361.0 -0.068844 0.997632 -0.137667 0.990479 -0.206481 0.978465 -0.275293 0.961702
362.0 -0.034422 0.999407 -0.068844 0.997632 -0.103255 0.994662 -0.137667 0.990479
363.0 -0.017213 0.999852 -0.034422 0.999407 -0.051634 0.998667 -0.068844 0.997632
364.0 -0.000000 1.000000 -0.000000 1.000000 -0.000000 1.000000 -0.000000 1.000000
[365 rows x 8 columns]
Explanation:
This Python code defines a function fourier_features that takes an index (representing time points), a frequency (e.g., annual seasonality), and an order (number of harmonics to include) as inputs. It then generates Fourier features for the given time series data. The code computes sine and cosine terms up to the specified order, capturing cyclical patterns in the data.
The example demonstrates how to use the function to generate Fourier features for a simulated time series with annual seasonality. This can be helpful for machine learning models that need to learn and predict patterns in time series data.
原文地址: http://www.cveoy.top/t/topic/nUYG 著作权归作者所有。请勿转载和采集!