preprocess.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from dao.dao import load_cust_data_from_mysql, load_product_data_from_mysql, load_order_data_from_mysql
  2. from models.rank.data.config import CustConfig, ProductConfig
  3. import pandas as pd
  4. class DataProcess():
  5. def __init__(self, city_uuid):
  6. print("正在加载cust_info...")
  7. self._cust_data = load_cust_data_from_mysql(city_uuid)
  8. print("正在加载product_info...")
  9. self._product_data = load_product_data_from_mysql(city_uuid)
  10. print("正在加载order_info...")
  11. self._order_data = load_order_data_from_mysql(city_uuid)
  12. def data_process(self):
  13. """数据预处理"""
  14. # 1. 获取指定的特征组合
  15. self._cust_data = self._cust_data[CustConfig.FEATURE_COLUMNS]
  16. self._product_data = self._product_data[ProductConfig.FEATURE_COLUMNS]
  17. # 2. 数据清洗
  18. self._clean_cust_data()
  19. self._clean_product_data()
  20. # 3. 将零售户信息表与卷烟信息表进行笛卡尔积连接
  21. self._descartes()
  22. # 4. 根据order表中的信息给数据打标签
  23. self._labeled_data()
  24. # 5. 选取训练样本
  25. self._generate_train_data()
  26. def _clean_cust_data(self):
  27. """用户信息表数据清洗"""
  28. # 根据配置规则清洗数据
  29. for feature, rules, in CustConfig.CLEANING_RULES.items():
  30. if rules["type"] == "num":
  31. # 先将数值型字符串转换为数值
  32. self._cust_data[feature] = pd.to_numeric(self._cust_data[feature], errors="coerce")
  33. if rules["method"] == "fillna":
  34. if rules["opt"] == "fill":
  35. self._cust_data[feature] = self._cust_data[feature].fillna(rules["value"])
  36. elif rules["opt"] == "replace":
  37. self._cust_data[feature] = self._cust_data[feature].fillna(self._cust_data[rules["value"]])
  38. elif rules["opt"] == "mean":
  39. self._cust_data[feature] = self._cust_data[feature].fillna(self._cust_data[feature].mean())
  40. def _clean_product_data(self):
  41. """卷烟信息表数据清洗"""
  42. for feature, rules, in ProductConfig.CLEANING_RULES.items():
  43. if rules["type"] == "num":
  44. self._product_data[feature] = pd.to_numeric(self._product_data[feature], errors="coerce")
  45. if rules["method"] == "fillna":
  46. if rules["opt"] == "fill":
  47. self._product_data[feature] = self._product_data[feature].fillna(rules["value"])
  48. elif rules["opt"] == "mean":
  49. self._product_data[feature] = self._product_data[feature].fillna(self._product_data[feature].mean())
  50. def _descartes(self):
  51. """将零售户信息与卷烟信息进行笛卡尔积连接"""
  52. self._cust_data["descartes"] = 1
  53. self._product_data["descartes"] = 1
  54. self._descartes_data = pd.merge(self._cust_data, self._product_data, on="descartes").drop("descartes", axis=1)
  55. def _labeled_data(self):
  56. """根据order表信息给descartes_data数据打标签"""
  57. # 获取order表中的正样本组合
  58. order_combinations = self._order_data[["BB_RETAIL_CUSTOMER_CODE", "PRODUCT_CODE"]].drop_duplicates()
  59. order_set = set(zip(order_combinations["BB_RETAIL_CUSTOMER_CODE"], order_combinations["PRODUCT_CODE"]))
  60. # 在descartes_data中打标签:正样本为1,负样本为2
  61. self._descartes_data['label'] = self._descartes_data.apply(
  62. lambda row: 1 if (row['BB_RETAIL_CUSTOMER_CODE'], row['product_code']) in order_set else 0, axis=1)
  63. def _generate_train_data(self):
  64. """从descartes_data中生成训练数据"""
  65. positive_samples = self._descartes_data[self._descartes_data["label"] == 1]
  66. negative_samples = self._descartes_data[self._descartes_data["label"] == 0]
  67. positive_count = len(positive_samples)
  68. negative_count = min(2 * positive_count, len(negative_samples))
  69. print(positive_count)
  70. print(negative_count)
  71. # 随机抽取2倍正样本数量的负样本
  72. negative_samples_sampled = negative_samples.sample(n=negative_count, random_state=42)
  73. # 合并正负样本
  74. self._train_data = pd.concat([positive_samples, negative_samples_sampled], axis=0)
  75. self._train_data = self._train_data.sample(frac=1, random_state=42).reset_index(drop=True)
  76. # 保存训练数据
  77. self._train_data.to_csv("./models/rank/data/gbdt_data.csv", index=False)
  78. if __name__ == '__main__':
  79. processor = DataProcess("00000000000000000000000011445301")
  80. processor.data_process()