model.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import datetime
  2. import os
  3. import pickle
  4. import pandas as pd
  5. from flask_sqlalchemy.session import Session
  6. from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
  7. from sklearn.metrics import r2_score
  8. from sklearn.model_selection import train_test_split, cross_val_score
  9. from sqlalchemy import text
  10. from xgboost import XGBRegressor
  11. import logging
  12. from .database_models import Models, Datasets
  13. from .config import Config
  14. from .data_cleaner import clean_dataset
  15. # 加载模型
  16. def load_model(session, model_id):
  17. model = session.query(Models).filter(Models.ModelID == model_id).first()
  18. if not model:
  19. raise ValueError(f"Model with ID {model_id} not found.")
  20. with open(model.ModelFilePath, 'rb') as f:
  21. return pickle.load(f)
  22. # 模型预测
  23. def predict(session, input_data: pd.DataFrame, model_id):
  24. # 初始化模型
  25. ML_model = load_model(session, model_id) # 根据指定的模型名加载模型
  26. # model = load_model(model_id) # 根据指定的模型名加载模型
  27. predictions = ML_model.predict(input_data)
  28. return predictions.tolist()
  29. def check_dataset_overlap_with_test(dataset_df, data_type):
  30. """
  31. 检查数据集是否与测试集有重叠
  32. Args:
  33. dataset_df (DataFrame): 要检查的数据集
  34. data_type (str): 数据集类型 ('reflux' 或 'reduce')
  35. Returns:
  36. tuple: (重叠的行数, 重叠的行索引)
  37. """
  38. # 加载测试集
  39. if data_type == 'reflux':
  40. X_test = pd.read_csv('uploads/data/X_test_reflux.csv')
  41. Y_test = pd.read_csv('uploads/data/Y_test_reflux.csv')
  42. elif data_type == 'reduce':
  43. X_test = pd.read_csv('uploads/data/X_test_reduce.csv')
  44. Y_test = pd.read_csv('uploads/data/Y_test_reduce.csv')
  45. else:
  46. raise ValueError(f"不支持的数据类型: {data_type}")
  47. # 合并X_test和Y_test
  48. if data_type == 'reflux':
  49. test_df = pd.concat([X_test, Y_test], axis=1)
  50. else:
  51. test_df = pd.concat([X_test, Y_test], axis=1)
  52. # 确定用于比较的列
  53. compare_columns = [col for col in dataset_df.columns if col in test_df.columns]
  54. if not compare_columns:
  55. return 0, []
  56. # 查找重叠的行
  57. merged = dataset_df[compare_columns].merge(test_df[compare_columns], how='inner', indicator=True)
  58. overlapping_rows = merged[merged['_merge'] == 'both']
  59. # 获取重叠行在原始数据集中的索引
  60. if not overlapping_rows.empty:
  61. # 使用合并后的数据找回原始索引
  62. overlap_indices = []
  63. for _, row in overlapping_rows.iterrows():
  64. # 创建一个布尔掩码,用于在原始数据集中查找匹配的行
  65. mask = True
  66. for col in compare_columns:
  67. mask = mask & (dataset_df[col] == row[col])
  68. # 获取匹配行的索引
  69. matching_indices = dataset_df[mask].index.tolist()
  70. overlap_indices.extend(matching_indices)
  71. return len(set(overlap_indices)), list(set(overlap_indices))
  72. return 0, []
  73. # 计算模型评分
  74. def calculate_model_score(model_info):
  75. """
  76. 计算模型评分
  77. Args:
  78. model_info: 模型信息对象
  79. Returns:
  80. float: 模型的R²评分
  81. """
  82. # 加载模型
  83. with open(model_info.ModelFilePath, 'rb') as f:
  84. ML_model = pickle.load(f)
  85. # print("Model requires the following features:", model.feature_names_in_)
  86. # 数据准备
  87. if model_info.Data_type == 'reflux': # 反酸数据集
  88. # 加载保存的 X_test 和 Y_test
  89. X_test = pd.read_csv('uploads/data/X_test_reflux.csv')
  90. Y_test = pd.read_csv('uploads/data/Y_test_reflux.csv')
  91. print(X_test.columns) # 在测试时使用的数据的列名
  92. y_pred = ML_model.predict(X_test)
  93. elif model_info.Data_type == 'reduce': # 降酸数据集
  94. # 加载保存的 X_test 和 Y_test
  95. X_test = pd.read_csv('uploads/data/X_test_reduce.csv')
  96. Y_test = pd.read_csv('uploads/data/Y_test_reduce.csv')
  97. print(X_test.columns) # 在测试时使用的数据的列名
  98. y_pred = ML_model.predict(X_test)
  99. # 计算 R² 分数
  100. r2 = r2_score(Y_test, y_pred)
  101. return r2
  102. def train_and_save_model(session, model_type, model_name, model_description, data_type, dataset_id=None):
  103. try:
  104. if not dataset_id:
  105. # 创建新的数据集并复制数据,此过程将不立即提交
  106. dataset_id = save_current_dataset(session, data_type, commit=False)
  107. if data_type == 'reflux':
  108. current_table = 'current_reflux'
  109. elif data_type == 'reduce':
  110. current_table = 'current_reduce'
  111. # 从current数据集表中加载数据
  112. dataset = pd.read_sql_table(current_table, session.bind)
  113. elif dataset_id:
  114. # 从新复制的数据集表中加载数据
  115. dataset_table_name = f"dataset_{dataset_id}"
  116. dataset = pd.read_sql_table(dataset_table_name, session.bind)
  117. if dataset.empty:
  118. raise ValueError(f"Dataset {dataset_id} is empty or not found.")
  119. # 使用数据清理模块
  120. if data_type == 'reflux':
  121. X = dataset.iloc[:, 1:-1]
  122. y = dataset.iloc[:, -1]
  123. # target_column = -1 # 假设目标变量在最后一列
  124. # X, y, clean_stats = clean_dataset(dataset, target_column=target_column)
  125. elif data_type == 'reduce':
  126. X = dataset.iloc[:, 2:]
  127. y = dataset.iloc[:, 1]
  128. # target_column = 1 # 假设目标变量在第二列
  129. # X, y, clean_stats = clean_dataset(dataset, target_column=target_column)
  130. # 记录清理统计信息
  131. # logging.info(f"数据清理统计: {clean_stats}")
  132. # 训练模型
  133. model = train_model_by_type(X, y, model_type)
  134. # 保存模型到数据库
  135. model_id = save_model(session, model, model_name, model_type, model_description, dataset_id, data_type)
  136. # 所有操作成功后,手动提交事务
  137. session.commit()
  138. return model_name, model_id, dataset_id
  139. except Exception as e:
  140. # 如果在任何阶段出现异常,回滚事务
  141. session.rollback()
  142. raise e # 可选择重新抛出异常或处理异常
  143. def save_current_dataset(session, data_type, commit=True):
  144. """
  145. 创建一个新的数据集条目,并复制对应的数据类型表的数据,但不立即提交事务。
  146. Args:
  147. session (Session): SQLAlchemy session对象。
  148. data_type (str): 数据集的类型。
  149. commit (bool): 是否在函数结束时提交事务。
  150. Returns:
  151. int: 新保存的数据集的ID。
  152. """
  153. current_time = datetime.datetime.now()
  154. new_dataset = Datasets(
  155. Dataset_name=f"{data_type}_dataset_{current_time:%Y%m%d_%H%M%S}",
  156. Dataset_description=f"Automatically generated dataset for type {data_type}",
  157. Row_count=0,
  158. Status='pending',
  159. Dataset_type=data_type,
  160. Uploaded_at=current_time
  161. )
  162. session.add(new_dataset)
  163. session.flush()
  164. dataset_id = new_dataset.Dataset_ID
  165. source_table = data_type_table_mapping(data_type)
  166. new_table_name = f"dataset_{dataset_id}"
  167. session.execute(text(f"CREATE TABLE {new_table_name} AS SELECT * FROM {source_table};"))
  168. session.execute(text(f"UPDATE datasets SET status='Datasets upgraded success', row_count=(SELECT count(*) FROM {new_table_name}) WHERE dataset_id={dataset_id};"))
  169. if commit:
  170. session.commit()
  171. return dataset_id
  172. def data_type_table_mapping(data_type):
  173. """映射数据类型到对应的数据库表名"""
  174. if data_type == 'reduce':
  175. return 'current_reduce'
  176. elif data_type == 'reflux':
  177. return 'current_reflux'
  178. else:
  179. raise ValueError("Invalid data type provided.")
  180. def train_model_by_type(X, y, model_type):
  181. # 划分数据集
  182. # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  183. # 使用全部数据作为训练集
  184. X_train, y_train = X, y
  185. if model_type == 'RandomForest':
  186. # 随机森林的参数优化
  187. return train_random_forest(X_train, y_train)
  188. elif model_type == 'XGBR':
  189. # XGBoost的参数优化
  190. return train_xgboost(X_train, y_train)
  191. elif model_type == 'GBSTR':
  192. # 梯度提升树的参数优化
  193. return train_gradient_boosting(X_train, y_train)
  194. else:
  195. raise ValueError(f"Unsupported model type: {model_type}")
  196. def train_random_forest(X_train, y_train):
  197. best_score = -float('inf')
  198. best_n_estimators = None
  199. best_max_depth = None
  200. random_state = 43
  201. # 筛选最佳的树的数量
  202. for n_estimators in range(1, 20, 1):
  203. model = RandomForestRegressor(n_estimators=n_estimators, random_state=random_state)
  204. score = cross_val_score(model, X_train, y_train, cv=5).mean()
  205. if score > best_score:
  206. best_score = score
  207. best_n_estimators = n_estimators
  208. print(f"Best number of trees: {best_n_estimators}, Score: {best_score}")
  209. # 在找到的最佳树的数量基础上,筛选最佳的最大深度
  210. best_score = 0 # 重置最佳得分,为最大深度优化做准备
  211. for max_depth in range(1, 5, 1):
  212. model = RandomForestRegressor(n_estimators=best_n_estimators, max_depth=max_depth, random_state=random_state)
  213. score = cross_val_score(model, X_train, y_train, cv=5).mean()
  214. if score > best_score:
  215. best_score = score
  216. best_max_depth = max_depth
  217. print(f"Best max depth: {best_max_depth}, Score: {best_score}")
  218. # 使用最佳的树的数量和最大深度训练最终模型
  219. best_model = RandomForestRegressor(n_estimators=best_n_estimators, max_depth=best_max_depth,
  220. random_state=random_state)
  221. # 传入列名进行训练
  222. best_model.fit(X_train, y_train)
  223. # 指定传入的特征名
  224. best_model.feature_names_in_ = X_train.columns
  225. return best_model
  226. def train_xgboost(X_train, y_train):
  227. best_score = -float('inf')
  228. best_params = {'learning_rate': None, 'max_depth': None}
  229. random_state = 43
  230. for learning_rate in [0.01, 0.05, 0.1, 0.2]:
  231. for max_depth in range(3, 10):
  232. model = XGBRegressor(learning_rate=learning_rate, max_depth=max_depth, random_state=random_state)
  233. score = cross_val_score(model, X_train, y_train, cv=5).mean()
  234. if score > best_score:
  235. best_score = score
  236. best_params['learning_rate'] = learning_rate
  237. best_params['max_depth'] = max_depth
  238. print(f"Best parameters: {best_params}, Score: {best_score}")
  239. # 使用找到的最佳参数训练最终模型
  240. best_model = XGBRegressor(learning_rate=best_params['learning_rate'], max_depth=best_params['max_depth'],
  241. random_state=random_state)
  242. best_model.fit(X_train, y_train)
  243. return best_model
  244. def train_gradient_boosting(X_train, y_train):
  245. best_score = -float('inf')
  246. best_params = {'learning_rate': None, 'max_depth': None}
  247. random_state = 43
  248. for learning_rate in [0.01, 0.05, 0.1, 0.2]:
  249. for max_depth in range(3, 10):
  250. model = GradientBoostingRegressor(learning_rate=learning_rate, max_depth=max_depth, random_state=random_state)
  251. score = cross_val_score(model, X_train, y_train, cv=5).mean()
  252. if score > best_score:
  253. best_score = score
  254. best_params['learning_rate'] = learning_rate
  255. best_params['max_depth'] = max_depth
  256. print(f"Best parameters: {best_params}, Score: {best_score}")
  257. # 使用找到的最佳参数训练最终模型
  258. best_model = GradientBoostingRegressor(learning_rate=best_params['learning_rate'], max_depth=best_params['max_depth'],
  259. random_state=random_state)
  260. best_model.fit(X_train, y_train)
  261. return best_model
  262. def save_model(session, model, model_name, model_type, model_description, dataset_id, data_type, commit=False):
  263. """
  264. 保存模型到数据库,并将模型文件保存到磁盘。
  265. Args:
  266. session: 数据库会话
  267. model: 要保存的模型对象
  268. model_name: 模型的名称
  269. model_type: 模型的类型
  270. model_description: 模型的描述信息
  271. dataset_id: 数据集ID
  272. data_type: 数据类型
  273. commit: 是否提交事务
  274. Returns:
  275. int: 返回保存的模型ID
  276. """
  277. prefix_dict = {
  278. 'RandomForest': 'rf_model_',
  279. 'XGBR': 'xgbr_model_',
  280. 'GBSTR': 'gbstr_model_'
  281. }
  282. prefix = prefix_dict.get(model_type, 'default_model_')
  283. try:
  284. # 从配置中获取保存路径
  285. model_save_path = Config.MODEL_SAVE_PATH
  286. # 确保路径存在
  287. os.makedirs(model_save_path, exist_ok=True)
  288. # 获取当前时间戳
  289. timestamp = datetime.datetime.now().strftime('%m%d_%H%M')
  290. # 拼接完整的文件名
  291. file_name = os.path.join(model_save_path, f'{prefix}{timestamp}.pkl')
  292. # 保存模型到文件
  293. with open(file_name, 'wb') as f:
  294. pickle.dump(model, f)
  295. print(f"模型已保存至: {file_name}")
  296. # 创建模型数据库记录
  297. new_model = Models(
  298. Model_name=model_name,
  299. Model_type=model_type,
  300. Description=model_description,
  301. DatasetID=dataset_id,
  302. Created_at=datetime.datetime.now(),
  303. ModelFilePath=file_name,
  304. Data_type=data_type
  305. )
  306. # 添加记录到数据库
  307. session.add(new_model)
  308. session.flush()
  309. return new_model.ModelID
  310. except Exception as e:
  311. print(f"保存模型时发生错误: {str(e)}")
  312. raise
  313. if __name__ == '__main__':
  314. # 反酸模型预测
  315. # 测试 predict 函数
  316. input_data = pd.DataFrame([{
  317. "organic_matter": 5.2,
  318. "chloride": 3.1,
  319. "cec": 25.6,
  320. "h_concentration": 0.5,
  321. "hn": 12.4,
  322. "al_concentration": 0.8,
  323. "free_alumina": 1.2,
  324. "free_iron": 0.9,
  325. "delta_ph": -0.2
  326. }])
  327. model_name = 'RF_filt'
  328. Acid_reflux_result = predict(input_data, model_name)
  329. print("Acid_reflux_result:", Acid_reflux_result) # 预测结果
  330. # 降酸模型预测
  331. # 测试 predict 函数
  332. input_data = pd.DataFrame([{
  333. "pH": 5.2,
  334. "OM": 3.1,
  335. "CL": 25.6,
  336. "H": 0.5,
  337. "Al": 12.4
  338. }])
  339. model_name = 'rf_model_1214_1008'
  340. Acid_reduce_result = predict(input_data, model_name)
  341. print("Acid_reduce_result:", Acid_reduce_result) # 预测结果