协同过滤算法实现步骤
- 1.表示用户行为矩阵,即统计用户购买某种商品类型的数量
public double[] getNumByCustomer(Customer customer){
List<OrderItem> list =orderItemDao.findByCustomerAndAliveAndState(customer.getId(),1,2);
double [] vectore =new double[totalNum];
int index=0;
for(ProductType type:productTypes){
for(OrderItem orderItem:list){
if(orderItem.getProduct().getProductType().id==type.id){
vectore[index]=vectore[index]+orderItem.getNum();
}
}
return vectore;
}
- 2.用余弦距离计算每个用户与其它用户的行为相似度
下面代码是两个用户之间的相似度,进行遍历就可以获取全部相似度
public double countSimilarity(double [] a,double [] b){
double total=0;
double alength=0;
double blength=0;
for(int i=0;i<a.length;i++){
total=total+a[i]*b[i];
alength=alength+a[i]*a[i];
blength=blength+b[i]*b[i];
}
double down=Math.sqrt(alength)*Math.sqrt(blength);
double result=0;
if(down!=0){
result =total/down;