ModelService.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package com.example.services;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.example.controller.vo.DLModelVO;
  5. import com.example.controller.vo.ModelVO;
  6. import com.example.dao.*;
  7. import com.example.data.FitTestData;
  8. import com.example.data.LibsvmAdapter;
  9. import com.example.entity.*;
  10. import com.example.model.classification.*;
  11. import com.example.model.cluster.KmeansCluster;
  12. import com.example.model.helper.Utils;
  13. import com.example.model.regression.RFRegression;
  14. import com.example.services.pojo.DLGeneralModelPojo;
  15. import com.example.services.pojo.DLModelPojo;
  16. import com.example.services.pojo.ModelPojo;
  17. import com.example.util.Json2Object;
  18. import lombok.Data;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.apache.spark.ml.PipelineModel;
  21. import org.apache.spark.ml.classification.LogisticRegressionModel;
  22. import org.apache.spark.ml.clustering.KMeansModel;
  23. import org.springframework.beans.factory.annotation.Autowired;
  24. import org.springframework.stereotype.Component;
  25. import java.util.ArrayList;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.stream.Collectors;
  30. /**
  31. * Config-related service
  32. * Created by twenbo on 2016/11/21.
  33. */
  34. @Slf4j
  35. @Data
  36. @Component
  37. public class ModelService {
  38. @Autowired
  39. private ConfigDao configDao;
  40. @Autowired
  41. private FileInfoDao fileInfoDao;
  42. @Autowired
  43. private PictureFileDao pictureFileDao;
  44. @Autowired
  45. private ModelDao modelDao;
  46. @Autowired
  47. private ModelTypeDao modelTypeDao;
  48. @Autowired
  49. private DLModelDao dlModelDao;
  50. @Autowired
  51. private HeaderInfoDao headerInfoDao;
  52. @Autowired
  53. private LibsvmAdapter libsvmAdapter;
  54. @Autowired
  55. private DTClassification dtClassification;
  56. @Autowired
  57. private LRClassification lrClassification;
  58. @Autowired
  59. private RFClassification rfClassification;
  60. @Autowired
  61. private GDBTClassification gdbtClassification;
  62. @Autowired
  63. private KmeansCluster kmeansCluster;
  64. @Autowired
  65. private MulPerClassification mulPerClassification;
  66. @Autowired
  67. private NaiveBayesClassification naiveBayesClassification;
  68. @Autowired
  69. private RFRegression rfRegression;
  70. @Autowired
  71. private FitTestData fitTestData;
  72. @Autowired
  73. private FileService fileService;
  74. @Autowired
  75. private Utils utils;
  76. /**
  77. *
  78. * @param modelVO
  79. * @return
  80. */
  81. public int addModel(ModelVO modelVO){
  82. Model modelInfo = new Model();
  83. modelInfo.setFileInfoId(Integer.parseInt(modelVO.getFileInfoId()));
  84. modelInfo.setConfigId(Integer.parseInt(modelVO.getConfigId()));
  85. modelInfo.setModelName(modelVO.getModelName());
  86. modelInfo.setModelTypeId(Integer.parseInt(modelVO.getModelTypeId()));
  87. modelInfo.setTrained(false);
  88. modelInfo.setResOfModel(null);
  89. modelInfo.setModelPath(null);
  90. modelInfo.setArguments(JSON.toJSONString(modelVO.getArguments()));
  91. return modelDao.save(modelInfo).getId();
  92. }
  93. public int addDlModel(DLModelVO dlModelVO) {
  94. DLModel dlModel = new DLModel();
  95. dlModel.setModelTypeId(Integer.parseInt(dlModelVO.getModelTypeId()));
  96. dlModel.setPicFileId(Integer.parseInt(dlModelVO.getPicFileId()));
  97. dlModel.setModelName(dlModelVO.getModelName());
  98. dlModel.setTrained(false);
  99. dlModel.setResOfModel(null);
  100. dlModel.setModelPath(null);
  101. dlModel.setArguments(JSON.toJSONString(dlModelVO.getArguments()));
  102. return dlModelDao.save(dlModel).getId();
  103. }
  104. /**
  105. *
  106. * @param userId
  107. * @return
  108. */
  109. public List<ModelPojo> getAllModelByUserId(int userId){
  110. List<ModelPojo> rsl = configDao.findByUserId(userId).stream().map((config) -> {
  111. int configId = config.getId();
  112. String configName = config.getConfName();
  113. List<ModelPojo> modelPerConfig = modelDao.findByConfigId(configId).stream().map((model) -> {
  114. ModelType modelType = modelTypeDao.findById(model.getModelTypeId());
  115. int flag = -1;
  116. if(model.isTrained() && model.getResOfModel()!=null){
  117. flag = 1;
  118. }else if(model.isTrained() && model.getResOfModel()==null){
  119. flag = 0;
  120. }
  121. return new ModelPojo(String.valueOf(configId),
  122. configName,
  123. String.valueOf(model.getModelTypeId()),
  124. modelType != null ? modelType.getModelTypeName() : "",
  125. modelType != null ? modelType.getModelDetailName() : "",
  126. modelType != null ? modelType.getModelDetailDes() : "",
  127. modelType != null ? modelType.getModelDes() : "",
  128. String.valueOf(model.getId()),
  129. model.getModelName(),
  130. flag,
  131. new Json2Object().Json2HashMap(model.getArguments()),
  132. new Json2Object().Json2HashMap(model.getResOfModel()));
  133. }).collect(Collectors.toList());
  134. return modelPerConfig;
  135. }).reduce(new ArrayList<>(), (listA, listB) -> {
  136. listA.addAll(listB);
  137. return listA;
  138. });
  139. return rsl;
  140. }
  141. /**
  142. *
  143. * @param userId
  144. * @return
  145. */
  146. public List<DLGeneralModelPojo> getAllGeneralModelByUserId(int userId){
  147. List<PicFile> picFiles = pictureFileDao.findByUserId(userId);
  148. List<DLGeneralModelPojo> result = picFiles.stream().map(picFile -> {
  149. List<DLModel> dlModels = dlModelDao.findByPicFileId(picFile.getId());
  150. return dlModels.stream()
  151. .map(dlModel -> new DLGeneralModelPojo(String.valueOf(dlModel.getId()), dlModel.getModelName(), String.valueOf(picFile.getId()), picFile.getFileName(),dlModel.isTrained()
  152. ,dlModel.getResOfModel()!=null))
  153. .collect(Collectors.toList());
  154. }).reduce(new ArrayList<>(), (listA, listB) -> {
  155. listA.addAll(listB);
  156. return listA;
  157. });
  158. return result;
  159. }
  160. public DLModelPojo getDLModelDetailById(int modelId) {
  161. DLModel dlModel = dlModelDao.findById(modelId);
  162. return new DLModelPojo(String.valueOf(dlModel.getModelTypeId()),String.valueOf(dlModel.getPicFileId()),
  163. dlModel.getModelName(),dlModel.isTrained(),dlModel.getModelPath(),new Json2Object().Json2HashMap(dlModel.getResOfModel())
  164. ,new Json2Object().Json2HashMap(dlModel.getArguments()));
  165. }
  166. /**
  167. *
  168. * @param modelTypeName
  169. * @return
  170. */
  171. public List<ModelType> getModelTypeByModelTypeName(String modelTypeName) {
  172. return modelTypeDao.findByModelTypeName(modelTypeName);
  173. }
  174. /**
  175. *
  176. * @param modelId
  177. * @param modelName
  178. * @param modelTypeId
  179. * @return
  180. */
  181. public boolean changeModel(int modelId, String modelName, int modelTypeId){
  182. Model model = modelDao.findById(modelId);
  183. model.setModelName(modelName);
  184. model.setModelTypeId(modelTypeId);
  185. modelDao.save(model);
  186. return true;
  187. }
  188. /**
  189. *change status of isTrained
  190. * @param modelId
  191. * @return
  192. */
  193. public boolean changeStatusOfTrained(int modelId, boolean trained){
  194. Model model = modelDao.findById(modelId);
  195. model.setTrained(trained);
  196. modelDao.save(model);
  197. return true;
  198. }
  199. /**
  200. *
  201. * @param modelId
  202. * @param resOfModel
  203. * @param model
  204. * @return
  205. */
  206. public boolean updateResOfModel(int modelId, HashMap<String, String> resOfModel, Object model) throws Exception {
  207. // 将模型持久化(上传到hdfs)
  208. utils.storeModel(model,modelId);
  209. Model modelOfGet = modelDao.findById(modelId);
  210. //log.info("\n\nmodel:"+JSON.toJSONString(model)+"\n\n");
  211. //T.B.D.
  212. //modelOfGet.setModel(model);
  213. modelOfGet.setResOfModel(JSON.toJSONString(resOfModel));
  214. modelOfGet.setTrained(true);
  215. log.info("\n\nstore model result: "+modelOfGet.getResOfModel());
  216. modelDao.save(modelOfGet);
  217. return true;
  218. }
  219. public boolean trainTheModel(int modelId) throws Exception{
  220. //change training flag to true
  221. changeStatusOfTrained(modelId, true);
  222. Model trainingModel = modelDao.findById(modelId);
  223. ModelType modelType = modelTypeDao.findById(trainingModel.getModelTypeId());
  224. Config configInfo = configDao.findById(trainingModel.getConfigId());
  225. List<String> features = JSONObject.parseArray(configInfo.getFieldIds(),String.class).stream().map(fieldId ->
  226. headerInfoDao.findById(Integer.parseInt(fieldId)).getFieldName()).collect(Collectors.toList());
  227. //1. transfer file to libsvm
  228. log.info("\n\nTransfer to LibSVM...\n\n");
  229. String keyFeature = features.get(features.size()-1);
  230. features.remove(features.size()-1);
  231. int featureNum = features.size();
  232. String libsvm = libsvmAdapter.parquet2Libsvm(configInfo.getFileInfoId(), keyFeature, features.toArray(new String[0]));
  233. String modelDetailName = modelType.getModelDetailName();
  234. HashMap<String,String> modelArguments = new Json2Object().Json2HashMap(trainingModel.getArguments());
  235. boolean rsl = false;
  236. try {
  237. switch (modelDetailName) {
  238. case "LogisticRegression":
  239. /*
  240. * maxIter: Int,
  241. regParam: Float,
  242. elasticNetParam: Float
  243. * */
  244. LogisticRegressionModel lrModel = lrClassification.lrTraining(libsvm,
  245. Integer.parseInt(modelArguments.get("MaxIter")),
  246. Float.parseFloat(modelArguments.get("RegParam")),
  247. Float.parseFloat(modelArguments.get("ElasticNetParam")));
  248. log.info("\n\nstore Model result\n\n");
  249. HashMap<String,String> lrRst = lrClassification.lrResult(lrModel,modelId);
  250. log.info("\n\nupdate result of model\n\n");
  251. rsl = updateResOfModel(modelId, lrRst, lrModel);
  252. break;
  253. case "DecisionTree":
  254. /*
  255. * maxIter: Int,
  256. regParam: Float,
  257. elasticNetParam: Float
  258. * */
  259. PipelineModel dtModel = dtClassification.dtTraining(libsvm,
  260. Integer.parseInt(modelArguments.get("Category")),
  261. Float.parseFloat(modelArguments.get("TrainingSetOccupy")));
  262. HashMap<String,String> dtResult = dtClassification.dtResult(dtModel, modelId);
  263. rsl = updateResOfModel(modelId, dtResult, dtModel);
  264. break;
  265. case "RandomForest":
  266. /*
  267. * maxIter: Int,
  268. regParam: Float,
  269. elasticNetParam: Float
  270. * */
  271. PipelineModel rfModel = rfClassification.dtTraining(libsvm,
  272. Integer.parseInt(modelArguments.get("Category")),
  273. Float.parseFloat(modelArguments.get("TrainingDataSetOccupy")));
  274. HashMap<String,String> rfResult = rfClassification.dtResult(rfModel, modelId);
  275. rsl = updateResOfModel(modelId,rfResult,rfModel);
  276. break;
  277. case "GBDT":
  278. /*
  279. * maxIter: Int,
  280. regParam: Float,
  281. elasticNetParam: Float
  282. * */
  283. PipelineModel gbtModel = gdbtClassification.dtTraining(libsvm,
  284. Integer.parseInt(modelArguments.get("Category")),
  285. Float.parseFloat(modelArguments.get("TrainingDataSetOccupy")));
  286. HashMap<String,String> gbtResult = gdbtClassification.dtResult(gbtModel, modelId);
  287. rsl = updateResOfModel(modelId,gbtResult,gbtModel);
  288. break;
  289. case "K-Means":
  290. KMeansModel kmeansModel = kmeansCluster.dtTraining(libsvm,
  291. Integer.parseInt(modelArguments.get("NumOfCluster")),
  292. Integer.parseInt(modelArguments.get("Seed")));
  293. HashMap<String,String> kmeansResult = kmeansCluster.dtResult(kmeansModel,modelId);
  294. rsl = updateResOfModel(modelId,kmeansResult,kmeansModel);
  295. break;
  296. case "MultilayerPerceptronClassifier":
  297. PipelineModel mlpc = mulPerClassification.dtTraining(libsvm,
  298. Integer.parseInt(modelArguments.get("Category")),
  299. Float.parseFloat(modelArguments.get("TrainingDataSetOccupy")), featureNum);
  300. HashMap<String,String> mlpcResult = mulPerClassification.dtResult(mlpc, modelId);
  301. rsl = updateResOfModel(modelId,mlpcResult,mlpc);
  302. break;
  303. case "NaiveBayes":
  304. PipelineModel nby = naiveBayesClassification.dtTraining(libsvm,
  305. Integer.parseInt(modelArguments.get("Category")),
  306. Float.parseFloat(modelArguments.get("TrainingDataSetOccupy")));
  307. HashMap<String,String> nbyResult = naiveBayesClassification.dtResult(nby, modelId);
  308. rsl = updateResOfModel(modelId,nbyResult,nby);
  309. break;
  310. case "RandomForestRegression":
  311. PipelineModel rfReg = rfRegression.dtTraining(libsvm,
  312. Integer.parseInt(modelArguments.get("Category")),
  313. Float.parseFloat(modelArguments.get("TrainingDataSetOccupy"))
  314. );
  315. HashMap<String,String> rfRegResult = rfRegression.dtResult(rfReg,modelId);
  316. rsl = updateResOfModel(modelId,rfRegResult,rfReg);
  317. break;
  318. default:
  319. rsl = false;
  320. }
  321. } catch (Exception e) {
  322. e.printStackTrace();
  323. changeStatusOfTrained(modelId, false);
  324. }
  325. if(!rsl){
  326. changeStatusOfTrained(modelId,false);
  327. }
  328. return rsl;
  329. }
  330. /**
  331. *
  332. * @param modelId
  333. */
  334. public boolean deleteModel(int modelId) {
  335. Model model = modelDao.findById(modelId);
  336. if(model == null){
  337. return false;
  338. }
  339. modelDao.delete(modelDao.findById(modelId));
  340. return true;
  341. }
  342. public List<Map<String, String>> useModel(int fileId, int modelId) throws Exception{
  343. List<Map<String,String>> res = fitTestData.transformData(fileId,modelId);
  344. // fileService.deleteFile(fileId);
  345. return res;
  346. }
  347. }