时间序列进阶特征工程/多步预测/异常检测1. 时间序列特征工程importpandasaspdimportnumpyasnpdefcreate_time_features(df,date_col):dfdf.copy()df[date_col]pd.to_datetime(df[date_col])df[hour]df[date_col].dt.hour df[day]df[date_col].dt.day df[day_of_week]df[date_col].dt.dayofweek df[month]df[date_col].dt.month df[is_weekend]df[day_of_week].isin([5,6]).astype(int)returndfdefcreate_lag_features(df,target_col,lags[1,7,14,30]):forlaginlags:df[f{target_col}_lag_{lag}]df[target_col].shift(lag)returndfdefcreate_rolling_features(df,target_col,windows[7,14,30]):forwindowinwindows:df[f{target_col}_rolling_mean_{window}]df[target_col].rolling(window).mean()df[f{target_col}_rolling_std_{window}]df[target_col].rolling(window).std()returndf2. 多步预测defdirect_multi_step(model,X_last,steps7):predictions[]forstepinrange(steps):predmodel.predict(X_last.reshape(1,-1))[0]predictions.append(pred)X_lastnp.roll(X_last,-1)X_last[-1]predreturnpredictionsdefrecursive_multi_step(model,X_last,steps7):predictions[]current_inputX_last.copy()for_inrange(steps):predmodel.predict(current_input.reshape(1,-1))[0]predictions.append(pred)current_inputnp.append(current_input[1:],pred)returnpredictions3. 时间序列异常检测fromsklearn.ensembleimportIsolationForestdefdetect_anomalies(data,column,contamination0.05):modelIsolationForest(contaminationcontamination,random_state42)data[anomaly]model.fit_predict(data[[column]])data[is_anomaly]data[anomaly]-1returndatadefstatistical_anomaly(data,column,window30,threshold3):rolling_meandata[column].rolling(window).mean()rolling_stddata[column].rolling(window).std()z_scores(data[column]-rolling_mean)/rolling_std data[is_anomaly]abs(z_scores)thresholdreturndata总结技术方法适用场景特征工程滞后/滚动/时间提升精度多步预测直接/递归未来预测异常检测IF/Z-Score故障检测