5 时间特征处理

https://www.kaggle.com/code/vanpatangan/orders-forecasting-challenge

1 时间特征周期性转换、ont-hot编码       

date_col = ['date']
for _col in date_col:
    date_col = pd.to_datetime(all_df[_col], errors='coerce')
    all_df[_col + "_year"] = date_col.dt.year.fillna(-1)
    all_df[_col + "_month"] = date_col.dt.month.fillna(-1)
    all_df[_col + "_day"] = date_col.dt.day.fillna(-1)
    all_df[_col + "week"] = date_col.dt.isocalendar().week.fillna(-1)
    all_df[_col + "_day_of_week"] = date_col.dt.dayofweek.fillna(-1)
    all_df[_col + "_day_of_year"] = date_col.dt.dayofyear.fillna(-1)
    
    for m in range(1,13):
        all_df[f'month_{m}']=(all_df[_col + "_month"]==m)
    
    for d in range(7):
        all_df[f'dayofweek_{d}']=(all_df[_col + "_day_of_week"]==d)

    # Apply sine and cosine transformations
    all_df[_col + '_year_sin'] = all_df[_col + "_year"] * np.sin(2 * np.pi * all_df[_col + "_year"])
    all_df[_col + '_year_cos'] = all_df[_col + "_year"] * np.cos(2 * np.pi * all_df[_col + "_year"])
    all_df[_col + '_month_sin'] = all_df[_col + "_month"] * np.sin(2 * np.pi * all_df[_col + "_month"]/12)
    all_df[_col + '_month_cos'] = all_df[_col + "_month"] * np.cos(2 * np.pi * all_df[_col + "_month"]/12)
    all_df[_col + '_day_sin'] = all_df[_col + "_day"] * np.sin(2 * np.pi * all_df[_col + "_day"]/30)
    all_df[_col + '_day_cos'] = all_df[_col + "_day"] * np.cos(2 * np.pi * all_df[_col + "_day"]/30)
    all_df[_col + '_day_of_week_sin'] = all_df[_col + "_day_of_week"] * np.sin(2 * np.pi * all_df[_col + "_day_of_week"]/7)
    all_df[_col + '_day_of_week_cos'] = all_df[_col + "_day_of_week"] * np.cos(2 * np.pi * all_df[_col + "_day_of_week"]/7)
    all_df[_col + '_day_of_year_sin'] = all_df[_col + "_day_of_year"] * np.sin(2 * np.pi * all_df[_col + "_day_of_year"]/365)
    all_df[_col + '_day_of_year_cos'] = all_df[_col + "_day_of_year"] * np.cos(2 * np.pi * all_df[_col + "_day_of_year"]/365)
    
    all_df.loc[(all_df[_col + "_day_of_week"].isin([5, 6]))&(all_df['holiday_name']=='no_holiday'), 'holiday_name'] = 'weekend'

    
    all_df.drop(_col, axis=1, inplace=True)

2 EDA

对数据有一个整体的认识:

def check(df):
    """
    Generates a concise summary of DataFrame columns.
    """
    # Use list comprehension to iterate over each column
    summary = [
        [col, df[col].dtype, df[col].count(), df[col].nunique(), 
         df[col].isnull().sum(), df.duplicated().sum()]
        for col in df.columns]

    # Create a DataFrame from the list of lists
    df_check = pd.DataFrame(summary, columns=["column", "dtype", "instances", "unique", "sum_null", "duplicates"])

    return df_check

print("Training Data Summary")
display(check(train_df))
print("Test Data Summary")
display(check(test_df))

3 参数选择

from sklearn.model_selection import RandomizedSearchCV, cross_val_score

# Define parameter grid for Randomized Search
param_dist = {
    'eta': uniform(0.01, 0.1),
    'max_depth': randint(3, 10),
    'subsample': uniform(0.7, 0.3),
    'colsample_bytree': uniform(0.7, 0.3),
    'n_estimators': randint(100, 500)
}

# Initialize RandomizedSearchCV
random_search = RandomizedSearchCV(
    xgb.XGBRegressor(objective='reg:squarederror', n_jobs=-1),
    param_distributions=param_dist,
    n_iter=50,
    cv=5,
    scoring='neg_mean_absolute_percentage_error',
    n_jobs=-1,
    random_state=42,
    verbose=0
)

# Fit RandomizedSearchCV
random_search.fit(X_train_scaled, y_train)

# Get the best model
best_model = random_search.best_estimator_

# Perform crossvalidation
kf = KFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(best_model, X_train_scaled, y_train, 
                            cv=kf, scoring='neg_mean_absolute_percentage_error')
cv_mape = -cv_scores.mean()

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
神经网络在处理时间序列数据时需要进行特征工程来提取有用的信息。以下是一些常用的时间序列特征工程方法: 1. 平移(Shift):将时间序列向前或向后平移,可以用来创建滞后特征(Lag features),即当前时刻的特征值与过去时刻的特征值之间的关系。 2. 滑动窗口(Windowing):将时间序列划分为固定大小的窗口,然后在每个窗口上计算统计特征,如均值、标准差等。这可以捕捉到时间序列的局部模式。 3. 指数加权移动平均(Exponential Weighted Moving Average):对时间序列进行指数加权平滑处理,使得近期观测值具有更大的权重。这可以减少噪声对特征的影响。 4. 季节性分解(Seasonal Decomposition):将时间序列分解为趋势、季节性和残差三个部分,可以提取出季节性模式。 5. 小波变换(Wavelet Transform):将时间序列转换到小波域,可以获得不同尺度上的频率信息。 6. 自回归模型(Autoregressive Models):使用过去时刻的观测值作为输入来预测当前时刻的观测值,可以提取出时间序列的自相关性。 7. 傅里叶变换(Fourier Transform):将时间序列转换到频域,可以提取出不同频率上的信息。 这些特征工程方法可以结合使用,根据具体问题和数据的特点选择合适的方法来提取时间序列的特征。在构建神经网络模型时,这些特征可以作为输入来进行训练和预测。希望这些信息对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值