The first financial management course for programmers Python quantitative trading system combat
V: ititit111222333
package com.tarzan.recommend.core;
import com.tarzan.recommend.dto.RelateDTO; import org.assertj.core.util.Lists;
import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream;
/ * *
- The core algorithm
- @author tarzan
- @ version 1.0
- Luoyang Tulian Technology Co., LTD
- @copyright (c) 2019 LuoYang TuLian Co’Ltd Inc. All rights reserved.
- @date 2020/7/31
- @ since JDK1.8
*/ public class CoreMath {
Public List<Integer> recommend(Integer userId, List<RelateDTO> List) {// find the nearest userId Map<Double, Integer> distances = computeNearestNeighbor(userId, list); Integer nearest = distances.values().iterator().next(); Map<Integer, List<RelateDTO>> userMap=list.stream().collect(Collectors.groupingBy(RelateDTO::getUseId)); // List<Integer> neighborItemList = userMap.get(nearest).stream().map(e->e.getModuleId()).collect(Collectors.toList()); // List of movies that the specified user has seen List<Integer> userItemList = userMap.get(userId).stream().map(e->e.getModuleId()).collect(Collectors.toList());; List<Integer> shameshamelist = new ArrayList<>(); for (Integer item : neighborItemList) { if (! userItemList.contains(item)) { recommendList.add(item); } } Collections.sort(recommendList); return recommendList; } /** * When given a userId, * @param userId * @param list * @return */ private Map<Double, Integer> computeNearestNeighbor(Integer userId, List<RelateDTO> list) { Map<Integer, List<RelateDTO>> userMap=list.stream().collect(Collectors.groupingBy(RelateDTO::getUseId)); Map<Double, Integer> distances = new TreeMap<>(); userMap.forEach((k,v)->{ if(k! =userId){ double distance = pearson_dis(v,userMap.get(userId)); distances.put(distance, k); }}); return distances; } private double pearson_dis(List<RelateDTO> xList, List<RelateDTO> yList) { List<Integer> xs= Lists.newArrayList(); List<Integer> ys= Lists.newArrayList(); xList.forEach(x->{ yList.forEach(y->{ if(x.getModuleId()==y.getModuleId()){ xs.add(x.getIndex()); ys.add(y.getIndex()); }}); }); return getRelate(xs,ys); } /** * Pearson correlation coefficient calculation * * @param XS * @Param ys * @return {@link Double} * @throws * @author Tarzan * @date 2020 July 31 17:03:20 */ public static Double getRelate(List<Integer> xs, List<Integer> ys){ int n=xs.size(); double Ex= xs.stream().mapToDouble(x->x).sum(); double Ey=ys.stream().mapToDouble(y->y).sum(); double Ex2=xs.stream().mapToDouble(x->Math.pow(x,2)).sum(); double Ey2=ys.stream().mapToDouble(y->Math.pow(y,2)).sum(); double Exy= IntStream.range(0,n).mapToDouble(i->xs.get(i)*ys.get(i)).sum(); double numerator=Exy-Ex*Ey/n; double denominator=Math.sqrt((Ex2-Math.pow(Ex,2)/n)*(Ey2-Math.pow(Ey,2)/n)); If (denominator = = 0) return 0.0; return numerator/denominator; }Copy the code
}