a.txt2,8,3.02,26,4.02,27,4.02,35,4.02,42,3.02,66,5.02,67,2.02,69,4.02,85,3.02,101,5.02,108,4.02,113,3.02,117,5.04,145,2.05,152,5.05,4,5.06,75,5.07,181,5.0dataset.mfunction[B]=dataset(A)fori=1:10000B(A(i,1),A(i,2))=A(i,3);endprocess.mloadNetflix.mat;[t1,t2]=size(B);user_sim=[];fori=1:t1-1forj=i+1:t1user_sim(i,j)=simliarity(B,i,j);user_sim(j,i)=user_sim(i,j);endendnum_predict=0;number=[30];%[1020304050607080];pre_rating=0;forp=1:length(number)sum_erro=0;MAE=0;RMSE=0;sum_RMSE_erro=0;load('testRating.txt');fori=1:length(testRating)pre_rating=predict(B,user_sim,testRating(i,1),testRating(i,2),number(p));if(pre_rating~=0)num_predict=num_predict+1;endsum_erro=sum_erro+abs(pre_rating-testRating(i,3));sum_RMSE_erro=sum_RMSE_erro+(pre_rating-testRating(i,3))^2;iftestRating(i,2)==8testRating(i,1)testRating(i,2)testRating(i,3)pre_ratingendendfprintf('CF邻居个数等于30的平均预测误差是:\n\n');MAE=sum_erro/num_predictRMSE=sqrt(sum_RMSE_erro/num_predict)coverage=num_predict/length(testRating)endsimliarity.mfunction[sim]=simliarity(B,tar_user_id,pre_user_id)[t1,t2]=size(B);co_rating_number=0;co_item=[];sum_tar_user=0;sum_pre_user=0;avg_tar_user=0;avg_pre_user=0;forj=1:t2if(B(tar_user_id,j)~=0)(B(pre_user_id,j)~=0)co_rating_number=co_rating_number+1;sum_tar_user=sum_tar_user+B(tar_user_id,j);sum_pre_user=sum_pre_user+B(pre_user_id,j);co_item(1,co_rating_number)=j;endendif(co_rating_number==0)sim=0;elseavg_tar_user=sum_tar_user/co_rating_number;avg_pre_user=sum_pre_user/co_rating_number;numerator=0;%分子denominator1=0;denominator2=0;denominator=0;%分母fori=1:co_rating_numberitem_id=co_item(1,i);numerator=numerator+(B(tar_user_id,item_id)-avg_tar_user)*(B(pre_user_id,item_id)-avg_pre_user);denominator1=denominator1+(B(tar_user_id,item_id)-1avg_tar_user)^2;denominator2=denominator2+(B(pre_user_id,item_id)-avg_pre_user)^2;enddenominator=sqrt(denominator1)*sqrt(denominator2);if(denominator==0)sim=0;elsesim=numerator/denominator;endendpredict.mfunction[pre_rating]=predict(B,user_sim,tar_user_id,tar_item_id,nu)%首先,找出对目标项目有过评分的用户users[t1,t2]=size(B);n=0;users=[];fori=1:t1if(B(i,tar_item_id)~=0)(i~=tar_user_id)n=n+1;users(n,1)=i;users(n,2)=user_sim(i,tar_user_id);endendusers=sort_weight(users);num_neib=nu;%设置邻居个数ifnum_neib>nnum_neib=n;end%预测numerator=0;%分子denominator=0;%分母%计算目标用户的平均评分sum_tar=0;num_tar=0;avg_tar=0;forj=1:t2ifB(tar_user_id,j)~=0num_tar=num_tar+1;sum_tar=sum_tar+B(tar_user_id,j);endendifnum_tar==0avg_tar=0;elseavg_tar=sum_tar/num_tar;endfori=1:num_neib%计算预测用户的平均评分pre_use_id=users(i,1);sum_pre=0;num_pre=0;avg_pre=0;forj=1:t2ifB(pre_use_id,j)~=0num_pre=num_pre+1;sum_pre=sum_pre+B(pre_use_id,j);endendifnum_pre==0avg_pre=0;elseavg_pre=sum_pre/num_pre;endnumerator=numerator+users(i,2)*(B(pre_use_id,tar_item_id)-avg_pre);denominator=denominator+abs(users(i,2));endifdenominator==0pre_rating=0;elsepre_rating=avg_tar+numerator/denominator;end2