gbdt_lr_inference.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import gc
  2. import joblib
  3. # from dao import Redis, get_product_by_id, get_custs_by_ids, load_cust_data_from_mysql
  4. from database import RedisDatabaseHelper, MySqlDao
  5. from models.rank.data import DataLoader
  6. from models.rank.data import ProductConfig, CustConfig, ShopConfig, ImportanceFeaturesMap
  7. from models.rank.data.utils import one_hot_embedding, sample_data_clear
  8. import numpy as np
  9. import pandas as pd
  10. from sklearn.preprocessing import StandardScaler
  11. import shap
  12. from tqdm import tqdm
  13. from utils import split_relation_subtable
  14. import os
  15. import tempfile
  16. class GbdtLrModel:
  17. def __init__(self, model_path):
  18. self.load_model(model_path)
  19. self.redis = RedisDatabaseHelper().redis
  20. self._mysql_dao = MySqlDao()
  21. self._explanier = None
  22. def load_model(self, model_path):
  23. models = joblib.load(model_path)
  24. self.gbdt_model, self.lr_model, self.onehot_encoder = models["lgbm_model"], models["lr_model"], models["onehot_encoder"]
  25. def get_cust_and_product_data(self, city_uuid, product_id):
  26. """从商户数据库中获取指定城市所有商户的id"""
  27. self.product_data = self._mysql_dao.get_product_by_id(city_uuid, product_id)[ProductConfig.FEATURE_COLUMNS]
  28. self.custs_data = self._mysql_dao.load_cust_data(city_uuid)[CustConfig.FEATURE_COLUMNS]
  29. def generate_feats_map(self, product_data, cust_data):
  30. """组合卷烟、商户特征矩阵"""
  31. # 笛卡尔积联合
  32. cust_data["descartes"] = 1
  33. product_data["descartes"] = 1
  34. feats_map = pd.merge(cust_data, product_data, on="descartes").drop("descartes", axis=1)
  35. # recall_cust_list = feats_map["BB_RETAIL_CUSTOMER_CODE"].to_list()
  36. feats_map.drop('BB_RETAIL_CUSTOMER_CODE', axis=1, inplace=True)
  37. feats_map.drop('product_code', axis=1, inplace=True)
  38. # onehot编码
  39. onehot_feats = {**CustConfig.ONEHOT_CAT, **ProductConfig.ONEHOT_CAT, **ShopConfig.ONEHOT_CAT}
  40. onehot_columns = list(onehot_feats.keys())
  41. numeric_columns = feats_map.drop(onehot_columns, axis=1).columns
  42. feats_map = one_hot_embedding(feats_map, onehot_feats)
  43. # 数字特征归一化
  44. if len(numeric_columns) != 0:
  45. scaler = StandardScaler()
  46. feats_map[numeric_columns] = scaler.fit_transform(feats_map[numeric_columns])
  47. return feats_map
  48. def get_recommend_list(self, recommend_sample, recall_list):
  49. # gbdt_preds = self.gbdt_model.apply(recommend_sample)[:, :, 0]
  50. # gbdt_feats_encoded = self.onehot_encoder.transform(gbdt_preds)
  51. # scores = self.lr_model.predict_proba(gbdt_feats_encoded)[:, 1]
  52. gbdt_preds = self.gbdt_model.predict(recommend_sample, pred_leaf=True)
  53. gbdt_feats_encoded = self.onehot_encoder.transform(gbdt_preds)
  54. scores = self.lr_model.predict_proba(gbdt_feats_encoded)[:, 1]
  55. recommend_list = []
  56. for cust_id, score in zip(recall_list, scores):
  57. recommend_list.append({cust_id: float(score)})
  58. recommend_list.append({"cust_code": cust_id, "recommend_score": score})
  59. recommend_list = sorted(
  60. [item for item in recommend_list if "recommend_score" in item],
  61. key=lambda x: x["recommend_score"],
  62. reverse=True
  63. )
  64. return recommend_list
  65. def inference_from_sample(self, sample):
  66. inference_sample = sample.drop(columns=["BB_RETAIL_CUSTOMER_CODE", "product_code", "sale_qty", "product_name", "cust_code"])
  67. onehot_feats = {**CustConfig.ONEHOT_CAT, **ProductConfig.ONEHOT_CAT, **ShopConfig.ONEHOT_CAT}
  68. onehot_columns = list(onehot_feats.keys())
  69. numeric_columns = inference_sample.drop(onehot_columns, axis=1).columns
  70. inference_sample = one_hot_embedding(inference_sample, onehot_feats)
  71. print(numeric_columns)
  72. # 数字特征归一化
  73. if len(numeric_columns) != 0:
  74. scaler = StandardScaler()
  75. inference_sample[numeric_columns] = scaler.fit_transform(inference_sample[numeric_columns])
  76. gbdt_preds = self.gbdt_model.predict(inference_sample, pred_leaf=True)
  77. gbdt_feats_encoded = self.onehot_encoder.transform(gbdt_preds)
  78. scores = self.lr_model.predict_proba(gbdt_feats_encoded)[:, 1]
  79. sample["score"] = scores
  80. return sample[["cust_code", "product_code", "product_name", "sale_qty", "score"] + ProductConfig.FEATURE_COLUMNS]
  81. def generate_feats_importance(self):
  82. """生成特征重要性"""
  83. # 获取GBDT模型的特征重要性
  84. feats_importance = self.gbdt_model.feature_importances_
  85. # 获取特征名称
  86. feats_names = self.gbdt_model.feature_name_
  87. importance_dict = dict(zip(feats_names, feats_importance))
  88. onehot_feats = {**CustConfig.ONEHOT_CAT, **ShopConfig.ONEHOT_CAT, **ProductConfig.ONEHOT_CAT}
  89. for feat, categories in onehot_feats.items():
  90. related_columns = [f"{feat}_{item}" for item in categories]
  91. if related_columns:
  92. # 合并类别重要性
  93. combined_importance = sum(importance_dict[col] for col in related_columns)
  94. # 删除onehot类别列
  95. for col in related_columns:
  96. del importance_dict[col]
  97. # 添加合并后的重要性
  98. importance_dict[feat] = combined_importance
  99. # 排序
  100. sorted_importance = sorted(importance_dict.items(), key=lambda x: x[1], reverse=True)
  101. # 输出特征重要性
  102. cust_features_importance = []
  103. product_features_importance = []
  104. for feat, importance in sorted_importance:
  105. if feat in list(ImportanceFeaturesMap.CUSTOM_FEATURES_MAP.keys()):
  106. cust_features_importance.append({ImportanceFeaturesMap.CUSTOM_FEATURES_MAP[feat]: float(importance)})
  107. if feat in list(ImportanceFeaturesMap.SHOPING_FEATURES_MAP.keys()):
  108. cust_features_importance.append({ImportanceFeaturesMap.SHOPING_FEATURES_MAP[feat]: float(importance)})
  109. if feat in list(ImportanceFeaturesMap.PRODUCT_FEATRUES_MAP.keys()):
  110. product_features_importance.append({ImportanceFeaturesMap.PRODUCT_FEATRUES_MAP[feat]: float(importance)})
  111. return cust_features_importance, product_features_importance
  112. def generate_shap_interance(self, data):
  113. # 初始化SHAP解释器
  114. if self._explanier is None:
  115. self._explanier = shap.TreeExplainer(self.gbdt_model)
  116. # 获取数据基本信息
  117. n_samples = len(data)
  118. n_features = len(data.columns)
  119. batch_size = 500 # 可根据内存调整
  120. # 创建临时内存映射文件
  121. # temp_dir = tempfile.mkdtemp()
  122. temp_dir = "./data/tmp"
  123. temp_file = os.path.join(temp_dir, "shap_interaction_temp.dat")
  124. if os.path.exists(temp_dir):
  125. os.remove(temp_file)
  126. else:
  127. os.makedirs(temp_dir)
  128. try:
  129. # 预创建内存映射文件
  130. fp_shape = (n_samples, n_features, n_features)
  131. fp = np.memmap(temp_file, dtype=np.float32,
  132. mode='w+',
  133. shape=fp_shape)
  134. # 分批计算并存储SHAP交互值
  135. for i in tqdm(range(0, n_samples, batch_size), desc="计算SHAP交互值..."):
  136. batch_data = data.iloc[i:i+batch_size]
  137. batch_interaction = self._explanier.shap_interaction_values(batch_data)
  138. fp[i:i+len(batch_interaction)] = batch_interaction.astype(np.float32)
  139. fp.flush() # 确保数据写入磁盘
  140. # 分批计算均值
  141. mean_interaction = np.zeros((n_features, n_features), dtype=np.float32)
  142. for i in tqdm(range(0, n_samples, batch_size), desc="计算均值..."):
  143. batch = fp[i:i+batch_size] # 读取批数据并取绝对值
  144. mean_interaction += batch.sum(axis=0) # 按批累加
  145. mean_interaction /= n_samples # 计算最终均值
  146. # 构建交互矩阵DataFrame
  147. interaction_df = pd.DataFrame(
  148. mean_interaction,
  149. index=data.columns,
  150. columns=data.columns
  151. )
  152. # 分离卷烟和商户特征
  153. product_feats = [
  154. f"{feat}_{item}"
  155. for feat, categories in ProductConfig.ONEHOT_CAT.items()
  156. for item in categories
  157. ]
  158. cust_feats = [
  159. f"{feat}_{item}"
  160. for feat, categories in {**CustConfig.ONEHOT_CAT, **ShopConfig.ONEHOT_CAT}.items()
  161. for item in categories
  162. ]
  163. # 提取交叉区块
  164. cross_matrix = interaction_df.loc[product_feats, cust_feats]
  165. # 转换为长格式
  166. stacked = cross_matrix.stack().reset_index()
  167. stacked.columns = ['product_feat', 'cust_feat', 'relation']
  168. # 过滤掉零值或NaN的配对
  169. filtered = stacked[
  170. (stacked['relation'].abs() > 1e-6) & # 排除极小值
  171. (~stacked['relation'].isna()) # 排除NaN
  172. ].copy()
  173. # 排序结果
  174. results = (
  175. filtered
  176. .sort_values('relation', ascending=False)
  177. .to_dict('records')
  178. )
  179. # 替换特征名称
  180. feats_name_map = {
  181. **ImportanceFeaturesMap.CUSTOM_FEATURES_MAP,
  182. **ImportanceFeaturesMap.SHOPING_FEATURES_MAP,
  183. **ImportanceFeaturesMap.PRODUCT_FEATRUES_MAP
  184. }
  185. for item in results:
  186. # 处理产品特征名
  187. product_f = item["product_feat"]
  188. product_infos = product_f.split("_")
  189. item["product_feat"] = f"{feats_name_map['_'.join(product_infos[:-1])]}({product_infos[-1]})"
  190. # 处理客户特征名
  191. cust_f = item["cust_feat"]
  192. cust_infos = cust_f.split("_")
  193. item["cust_feat"] = f"{feats_name_map['_'.join(cust_infos[:-1])]}({cust_infos[-1]})"
  194. # 返回最终结果
  195. return pd.DataFrame(results, columns=['product_feat', 'cust_feat', 'relation'])
  196. finally:
  197. # 清理临时文件
  198. try:
  199. del fp # 必须先删除内存映射对象
  200. gc.collect()
  201. os.remove(temp_file)
  202. os.rmdir(temp_dir)
  203. except Exception as e:
  204. print(f"清理临时文件时出错: {e}")
  205. if __name__ == "__main__":
  206. model_path = "./models/rank/weights/00000000000000000000000011445301/gbdtlr_model.pkl"
  207. city_uuid = "00000000000000000000000011445301"
  208. product_id = "110102"
  209. gbdt_sort = GbdtLrModel(model_path)
  210. # gbdt_sort.sort(city_uuid, product_id)
  211. # cust_features_importance, product_features_importance = gbdt_sort.generate_feats_importance()
  212. # cust_df = pd.DataFrame([
  213. # {"Features": list(item.keys())[0], "Importance": list(item.values())[0]}
  214. # for item in cust_features_importance
  215. # ])
  216. # cust_df.to_csv("./data/cust_feats.csv", index=False)
  217. # product_df = pd.DataFrame([
  218. # {"Features": list(item.keys())[0], "Importance": list(item.values())[0]}
  219. # for item in product_features_importance
  220. # ])
  221. # product_df.to_csv("./data/product_feats.csv", index=False)
  222. data, _ = DataLoader("./data/gbdt/train_data.csv").split_dataset()
  223. data = data["data"].sample(n=300, replace=True, random_state=42)
  224. data.to_csv("./data/data.csv", index=False)
  225. # data = data["data"]
  226. result = gbdt_sort.generate_shap_interance(data)
  227. print("保存结果")
  228. result.to_csv("./data/feats_interaction.csv", index=False, encoding='utf-8-sig')
  229. split_relation_subtable(result, "./data")