vov_h24_analyse.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import numpy as np
  2. import pandas as pd
  3. from scipy.optimize import minimize
  4. from sklearn.metrics import r2_score
  5. from sklearn.model_selection import train_test_split
  6. import pickle
  7. all_feature_names = ["1_vovh0", "2_vovh0", "2_vovh1", "3_vovh0", "3_vovh1", "3_vovh2", "4_vovh0", "4_vovh1", "4_vovh2",
  8. "4_vovh3", "6_vovh0", "6_vovh1", "6_vovh6", "12_vovh0", "12_vovh1", "12_vovh12", "24_vovh0",
  9. "24_vovh1", "24_vovh2", "24_vovh3", "24_vovh6", "24_vovh12", "24_vovh24", "48_vovh0", "48_vovh1",
  10. "48_vovh2", "48_vovh3", "48_vovh6", "48_vovh12", "48_vovh24", "48_vovh48", "1_vovd0", "2_vovd0",
  11. "3_vovd0", "4_vovd0", "5_vovd0", "2_vovd1", "3_vovd1", "4_vovd1", "5_vovd1", "3_vovd2", "4_vovd2",
  12. "5_vovd2", "1_vovh_分母", "1_vovh0分子", "2_vovh_分母", "2_vovh0分子", "2_vovh1分子",
  13. "3_vovh_分母", "3_vovh0分子", "3_vovh1分子", "3_vovh2分子", "4_vovh_分母", "4_vovh0分子",
  14. "4_vovh1分子", "4_vovh2分子", "4_vovh3分子", "6_vovh_分母", "6_vovh0分子", "6_vovh1分子",
  15. "6_vovh6分子", "12_vovh_分母", "12_vovh0分子", "12_vovh1分子", "12_vovh12分子", "24_vovh_分母",
  16. "24_vovh0分子", "24_vovh1分子", "24_vovh2分子", "24_vovh3分子", "24_vovh6分子", "24_vovh12分子",
  17. "24_vovh24分子", "48_vovh_分母", "48_vovh0分子", "48_vovh1分子", "48_vovh2分子", "48_vovh3分子",
  18. "48_vovh6分子", "48_vovh12分子", "48_vovh24分子", "48_vovh48分子", "1_vovd0_分母", "1_vovd0_分子",
  19. "2_vovd0_分母", "2_vovd0_分子", "3_vovd0_分母", "3_vovd0_分子", "4_vovd0_分母", "4_vovd0_分子",
  20. "5_vovd0_分母", "5_vovd0_分子", "2_vovd1_分母", "2_vovd1_分子", "3_vovd1_分母", "3_vovd1_分子",
  21. "4_vovd1_分母", "4_vovd1_分子", "5_vovd1_分母", "5_vovd1_分子", "3_vovd2_分母", "3_vovd2_分子",
  22. "4_vovd2_分母", "4_vovd2_分子", "5_vovd2_分母", "5_vovd2_分子"]
  23. # feature_names = ["1_vovh0",
  24. # "2_vovh0", "2_vovh1",
  25. # "3_vovh0", "3_vovh1", "3_vovh2",
  26. # "4_vovh0", "4_vovh1", "4_vovh2", "4_vovh3",
  27. # "6_vovh0", "6_vovh1", "6_vovh6",
  28. # "12_vovh0", "12_vovh1", "12_vovh12",
  29. # "24_vovh0", "24_vovh1", "24_vovh2", "24_vovh3", "24_vovh6", "24_vovh12", "24_vovh24",
  30. # "48_vovh0", "48_vovh1", "48_vovh2", "48_vovh3", "48_vovh6", "48_vovh12", "48_vovh24", "48_vovh48",
  31. # "1_vovd0", "2_vovd0", "3_vovd0",
  32. # "2_vovd1", "3_vovd1"
  33. # ]
  34. feature_names = ["1_vovh0",
  35. "2_vovh0", "2_vovh1",
  36. "3_vovh1", "3_vovh2",
  37. "4_vovh1", "4_vovh3",
  38. "6_vovh1", "6_vovh6",
  39. "12_vovh1", "12_vovh12",
  40. "24_vovh1", "24_vovh2", "24_vovh3", "24_vovh6", "24_vovh12", "24_vovh24",
  41. "48_vovh1", "48_vovh2", "48_vovh3", "48_vovh6", "48_vovh12", "48_vovh24", "48_vovh48",
  42. "1_vovd0",
  43. "2_vovd1", "3_vovd1"
  44. ]
  45. dt_list = ['20241014', '20241015', '20241016']
  46. hh_list = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12",
  47. "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]
  48. pd.set_option('display.max_rows', None) # 显示所有行
  49. pd.set_option('display.max_columns', None) # 显示所有列
  50. # 1. 加载数据
  51. def load_data(filepath: str) -> pd.DataFrame:
  52. return pd.read_csv(filepath)
  53. # 2. 数据预处理
  54. def preprocess_data(df, features, target):
  55. df_sorted = df.sort_values(by=target, ascending=False)
  56. x = df_sorted[features]
  57. y = df_sorted[target]
  58. top_k = df_sorted.head(100)
  59. return x, y, top_k
  60. # 3. 计算相关系数
  61. def calculate_correlations(df, features, target):
  62. correlations = {}
  63. for feature in features:
  64. # 删除 target 或 feature 列中任一为空的行
  65. valid_data = df[[target, feature]].dropna()
  66. # 如果没有有效数据,相关系数设为 0
  67. if len(valid_data) == 0:
  68. correlations[feature] = 0
  69. else:
  70. # 计算相关系数
  71. corr = valid_data[target].corr(valid_data[feature])
  72. correlations[feature] = corr if not np.isnan(corr) else 0
  73. # 转换为 Series 并按绝对值大小排序
  74. corr_series = pd.Series(correlations).abs().sort_values(ascending=False)
  75. return corr_series
  76. # 4. 定义动态加权和函数
  77. def dynamic_weighted_sum(features, weights):
  78. valid_features = ~np.isnan(features)
  79. if np.sum(valid_features) == 0:
  80. return np.nan
  81. normalized_weights = weights[valid_features] / np.sum(weights[valid_features])
  82. return np.sum(features[valid_features] * normalized_weights)
  83. # 5. 定义损失函数
  84. def mse_loss(y_true, y_pred):
  85. valid = ~np.isnan(y_true) & ~np.isnan(y_pred)
  86. return np.mean((y_true[valid] - y_pred[valid]) ** 2)
  87. # 6. 定义目标函数
  88. def objective(weights, X, y_true):
  89. y_pred = np.array([dynamic_weighted_sum(x, weights) for x in X.values])
  90. return mse_loss(y_true, y_pred)
  91. # 7. 搜索最佳权重
  92. def find_best_weights(X, y, initial_weights):
  93. result = minimize(objective, initial_weights, args=(X, y), method='Nelder-Mead')
  94. return result.x
  95. # 8. 评估模型
  96. def evaluate_model(X, y, weights):
  97. y_pred = np.array([dynamic_weighted_sum(x, weights) for x in X.values])
  98. valid = ~np.isnan(y) & ~np.isnan(y_pred)
  99. r2 = r2_score(y[valid], y_pred[valid])
  100. mse = mse_loss(y, y_pred)
  101. return r2, mse
  102. # 9. 保存模型
  103. def save_model(weights, features, file_path):
  104. model = {
  105. 'weights': weights,
  106. 'features': features,
  107. }
  108. with open(file_path, 'wb') as f:
  109. pickle.dump(model, f)
  110. # 10. 加载模型
  111. def load_model(file_path):
  112. with open(file_path, 'rb') as f:
  113. model = pickle.load(f)
  114. return model['weights'], model['features']
  115. def single_dt_handle(dt, df: pd.DataFrame):
  116. x, y, top_key = preprocess_data(df, feature_names, "vovh24")
  117. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
  118. correl = calculate_correlations(top_key, feature_names, "vovh24")
  119. print(f"{dt} Feature Correlations: ")
  120. print(correl.head(5))
  121. initial_weights = correl[feature_names].values
  122. best_weights = find_best_weights(x_train, y_train, initial_weights)
  123. # 评估模型
  124. r2_train, mse_train = evaluate_model(x_train, y_train, best_weights)
  125. r2_test, mse_test = evaluate_model(x_test, y_test, best_weights)
  126. print(f"\nTrain R² Score: {r2_train:.4f}, MSE: {mse_train:.4f}")
  127. print(f"Test R² Score: {r2_test:.4f}, MSE: {mse_test:.4f}")
  128. # 输出特征重要性
  129. print("\nFeature importance:")
  130. for feature, weight in zip(feature_names, best_weights):
  131. print(f"{feature}: {weight:.4f}")
  132. # 保存模型
  133. save_model(pd.Series(best_weights, index=feature_names), feature_names,
  134. '/Users/zhao/Desktop/vov/model/vovh24_linear_weighted_model.pkl')
  135. # 测试加载模型
  136. loaded_weights, loaded_features = load_model('/Users/zhao/Desktop/vov/model/vovh24_linear_weighted_model.pkl')
  137. print("\nLoaded model weights:")
  138. for feature, weight in loaded_weights.items():
  139. print(f"{feature}: {weight:.4f}")
  140. def _main():
  141. df_dict = {}
  142. for dt in dt_list:
  143. for hh in hh_list:
  144. key = f"{dt}{hh}"
  145. df = load_data(f"/Users/zhao/Desktop/vov/{key}.csv")
  146. df_dict[key] = df
  147. for key in df_dict:
  148. single_dt_handle(key, df_dict[key])
  149. return
  150. if __name__ == '__main__':
  151. _main()