技术:easyUI、jQuery、Spring、Struts、Hibernate、Mahout、MySQL
本Libimseti推荐系统使用数据、代码参考《Mahout in action》第五章内容。
系统可以从这里下载:libimesti推荐系统。
$('#ratingId').datagrid({ border:false, // fitColumns:true, singleSelect:true, // width:600, height:200, nowrap:false, // fit:true, pagination:true,//分页控件 pageSize:4, // 每页记录数,需要和pageList保持倍数关系 pageList:[4,8,12], rownumbers:true,//行号 // pagePosition:'bottom', url:'rating/rating_getRatingData.action', queryParams: { uid: userIdValue, selectgender:selectGender }, toolbar: "#toolbar", columns:[[ {field:'id',title:'用户ID',width:'50'}, {field:'gender',title:'用户Gender',width:'80'}, {field:'itemId',title:'档案ID',width:'120'}, {field:'pref',title:'档案评分',width:'150'}, {field:'itemGender',title:'档案Gender',width:'100'}, {field:'desc',title:'档案描述',width:'200',}, ]] });使用了toolbar,提供“添加”、“修改”和“删除“功能,使用分页组件用于分页显示查询数据;由于用户评分数据和用户性别数据是在两个表中,所以新建了一个中间类UserRating用于组装数据传入前台,代码如下:
public Map<String,Object> getRatingByUId(Integer uId,int rows,int page, char selectgender){ String hql = "from Rating r where UID="+uId +" order by r.uId,r.itemId"; String hqlCount ="select count(1) from Rating where UID="+uId; String hqlGender = "from Gender where UID="+uId; List<Rating> ratings = baseDAO.find(hql,new Object[]{},page,rows); List<UserRating> userRatings = new ArrayList<UserRating>(); if(ratings.size()<=0){ return null; } // 获取用户Gender // List<Gender> gender =genderDAO.find(hqlGender); char uGender = genderDAO.find(hqlGender).get(0).getGender(); char itemGender; UserRating ur = null; for(Rating rating:ratings){ ur= new UserRating(); ur.setId(uId); ur.setDesc(rating.getDesc()); ur.setItemId(rating.getItemId()); ur.setPref(rating.getPref()); ur.setGender(uGender); // 获取ITEM gender hqlGender="from Gender g where UID="+rating.getItemId(); itemGender =genderDAO.find(hqlGender).get(0).getGender(); ur.setItemGender(itemGender); userRatings.add(ur); } Map<String ,Object> jsonMap = new HashMap<String,Object>(); jsonMap.put("total", baseDAO.count(hqlCount)); jsonMap.put("rows", userRatings); return jsonMap; }这里的selectgender变量,本来是在页面添加的一个用于在查询时过滤性别的变量,后面感觉有点麻烦就没做了(性别数据在gender表,分页针对的是rating表);
// 用户在增加对其他项目评分的时候,需要检查是否该项目用户已经评过分 $.extend($.fn.validatebox.defaults.rules, { hasItem : { validator : function(value,param) { var uid = $('#uidId').val(); console.info("value:"+value+",user:"+uid); return hasItem(uid,value); }, message : '用户已对该项目评过分!' } }); // 检查用户是否对项目评过分 function hasItem(user,item){ if(isNaN(parseInt(item))){ return false; } var boolean =false; $.ajax({ // 获取数据 url : "rating/rating_hasItem.action", data : "uid=" + user+"&itemid="+item, dataType : "json", async:false, success : function(data) { console.info("用户"+user+"是否对项目"+item+"评分?"+data); // 设置 if(data==false||data=="false"){ boolean=true; } } }); return boolean; }这样在jsp页面就可以简单的使用下面的代码即可:
<input class="easyui-validatebox" type="text" name="itemid" id="itemidId" style="width:100px" data-options="required:true, validType:'hasItem'"/>
$('#filterId').click(function() { if(this.checked){ filter=true; }else{ filter=false; } console.info("filter:"+filter); });推荐同样使用easyUI的datagrid,其js如下:
$('#recommendId').datagrid({ border:false, singleSelect:true, height:180, nowrap:false, pagination:true,//分页控件 pageSize:4, // 每页记录数,需要和pageList保持倍数关系 pageList:[4,8,12], rownumbers:true,//行号 url:'rec/rec_getRecommendData.action', queryParams: { uid: userIdValue, filter:filter }, columns:[[ {field:'uid',title:'用户ID',width:'50'}, {field:'ugender',title:'用户Gender',width:'80'}, {field:'itemid',title:'档案ID',width:'120'}, {field:'pref',title:'档案评分',width:'150'}, {field:'itemgender',title:'档案Gender',width:'100'}, ]] });这里传入后台的参数中包括filter和uid,filter即是否使用过滤;
package com.fz.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.mahout.cf.taste.common.Refreshable; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.impl.model.file.FileDataModel; import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood; import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender; import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Recommender; import org.apache.mahout.cf.taste.similarity.UserSimilarity; import org.springframework.stereotype.Service; import com.fz.dao.BaseDAO; import com.fz.model.Gender; import com.fz.model.RecommendRating; import com.fz.util.GenderRescorer; import com.fz.util.Utils; /** * libimseti 推荐 * 使用《Mahout in action 》第五章代码 * 使用MySQL数据库作为数据源,则算法很慢 * @author fansy * */ @Service("recommend") public class LibimsetiRecommender implements Recommender { private Recommender delegate; private DataModel model; private FastIDSet men; private FastIDSet women; private FastIDSet usersRateMoreMen; private FastIDSet usersRateLessMen; @Resource private BaseDAO<Gender> genderDAO; private boolean filter=true; /** * 从数据库中获取DataModel * @return * @throws IOException * @throws TasteException * @throws NumberFormatException */ public LibimsetiRecommender() throws NumberFormatException, TasteException, IOException{ this(localDataModel()); } private static DataModel localDataModel() throws IOException { FileDataModel dataModel = new FileDataModel(new File(Utils.ratingsFile)); return dataModel; } public LibimsetiRecommender(DataModel model) throws TasteException, NumberFormatException, IOException{ UserSimilarity similarity = new EuclideanDistanceSimilarity(model); UserNeighborhood neighborhood = new NearestNUserNeighborhood(4,similarity,model);// 增大n值可以获得更多推荐 delegate = new GenericUserBasedRecommender(model,neighborhood,similarity); this.model=model; FastIDSet[] menWomen = GenderRescorer.parseMenWomen(new File(Utils.genderFile)); men = menWomen[0]; women = menWomen[1]; usersRateMoreMen = new FastIDSet(50000); usersRateLessMen = new FastIDSet(50000); } @Override public void refresh(Collection<Refreshable> alreadyRefreshed) { delegate.refresh(alreadyRefreshed); } @Override public List<RecommendedItem> recommend(long userID, int howMany) throws TasteException { IDRescorer rescorer= null; if(filter){ rescorer=new GenderRescorer(men,women,usersRateMoreMen,usersRateLessMen,userID,model); } return delegate.recommend(userID, howMany, rescorer); } /** * 推荐整合 * @throws TasteException */ public Map<String, Object> recommend(long userID,int rows,int page,boolean filter) throws TasteException{ this.filter=filter; String gHql = "from Gender g where g.uId=?"; List<RecommendedItem> recommend = recommend(userID,20); Map<String ,Object> jsonMap = new HashMap<String,Object>(); List<RecommendRating> tmp = new ArrayList<RecommendRating>(); RecommendRating rating =null; if(recommend.size()<=0){ rating = new RecommendRating(); rating.setUid(-1); rating.setUgender('U'); rating.setItemid(-1); rating.setItemgender('U'); rating.setPref(-1); tmp.add(rating); jsonMap.put("total", recommend.size()); jsonMap.put("rows", tmp); return jsonMap; } List<RecommendRating> recommendRatings = new ArrayList<RecommendRating>(); char uGender = genderDAO.get(gHql, new Object[]{(int)userID}).getGender(); for(RecommendedItem re:recommend){ rating = new RecommendRating(); rating.setUid(userID); rating.setUgender(uGender); rating.setItemid(re.getItemID()); rating.setItemgender(genderDAO.get(gHql, new Object[]{(int)re.getItemID()}).getGender()); rating.setPref(re.getValue()); recommendRatings.add(rating); } for(int i=(page-1)*rows;i<page*rows&&i<recommend.size();i++){ tmp.add(recommendRatings.get(i)); } jsonMap.put("total", recommend.size()); jsonMap.put("rows", tmp); return jsonMap; } @Override public List<RecommendedItem> recommend(long userID, int howMany, boolean includeKnownItems) throws TasteException { return delegate.recommend(userID, howMany, includeKnownItems); } @Override public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException { return delegate.recommend(userID, howMany, rescorer); } @Override public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer, boolean includeKnownItems) throws TasteException { return delegate.recommend(userID, howMany, rescorer, includeKnownItems); } @Override public float estimatePreference(long userID, long itemID) throws TasteException { IDRescorer rescorer= new GenderRescorer(men,women, usersRateMoreMen,usersRateLessMen,userID,model); return (float)rescorer.rescore(userID, itemID); } @Override public void setPreference(long userID, long itemID, float value) throws TasteException { delegate.setPreference(userID, itemID, value); } @Override public void removePreference(long userID, long itemID) throws TasteException { delegate.removePreference(userID, itemID); } @Override public DataModel getDataModel() { return delegate.getDataModel(); } public Recommender getDelegate() { return delegate; } public void setDelegate(Recommender delegate) { this.delegate = delegate; } public DataModel getModel() { return model; } public void setModel(DataModel model) { this.model = model; } public FastIDSet getMen() { return men; } public void setMen(FastIDSet men) { this.men = men; } public FastIDSet getWomen() { return women; } public void setWomen(FastIDSet women) { this.women = women; } public FastIDSet getUsersRateMoreMen() { return usersRateMoreMen; } public void setUsersRateMoreMen(FastIDSet usersRateMoreMen) { this.usersRateMoreMen = usersRateMoreMen; } public FastIDSet getUsersRateLessMen() { return usersRateLessMen; } public void setUsersRateLessMen(FastIDSet usersRateLessMen) { this.usersRateLessMen = usersRateLessMen; } public boolean isFilter() { return filter; } public void setFilter(boolean filter) { this.filter = filter; } }代码分析:
public boolean isFiltered(long id) { // TODO Auto-generated method stub return filterMen? men.contains(id):women.contains(id); }需要改为:
public boolean isFiltered(long id) { // TODO Auto-generated method stub return filterMen? (!men.contains(id)):(!women.contains(id)); }isFiltered方法其解释为
true
to exclude,
false
otherwise,这个解释和代码是不一样的;
$(function() { $('#catalogId') .datagrid( { border : false, fitColumns : true, singleSelect : true, width : 600, height : 250, nowrap : false, fit : true, pagination : true,// 分页控件 pageSize : 4, // 每页记录数,需要和pageList保持倍数关系 pageList : [ 4, 8, 12 ], rownumbers : true,// 行号 pagePosition : 'top', url : 'catalog/catalog_getTreeData.action', columns : [ [ { field : 'id', title : '节点ID', width : '40' }, { field : 'text', title : '节点名称', width : '120' }, { field : 'url', title : 'URL', width : '150' }, { field : 'pid', title : '父节点ID', width : '60' }, { field : 'iconCls', title : '图标', width : '100' }, { field : 'opt', title : '操作', width : '40', formatter : function(value, row, index) { var btn_edit = '<button type="button" onclick="update(' + row.id + ')">编辑</button>'; var btn_remove = '<button type="button" onclick="deleteRow(' + row.id + ')">删除</button>'; return btn_edit + btn_remove; } } ] ] }); });
点击添加按钮,可以对目录进行添加,其界面如下:
其中,图标使用combobox,其图标添加代码如下:
$('#iconId').combobox( { formatter : function(row) { var imageFile = 'themes/icons/' + row.icon; console.info('imageFile' + imageFile); return '<img class="item-img" src="' + imageFile + '"/> <span class="item-text">' + row.text + '</span>'; } });
分享,成长,快乐
转载请注明blog地址:http://blog.csdn.net/fansy1990