1. 程式人生 > >Mahout做協同過濾是的ID型別問題

Mahout做協同過濾是的ID型別問題

mahout做推薦的輸入只能是long型別,但在某些網站中,儲存的資料不是long型別,是string型別。
現在的手機APP,每個手機都有其device_id,也是string型別。如果能以string型別作為uid,即使使用者不註冊,不登入。只要採用device_id作為其uid,也可以做精準推薦。
mahout提供了一個介面,能把string轉為唯一的long型別資料,然後以map方式儲存起來,計算完成後再把long轉為string型別。

package test;  

import org.apache.mahout.cf.taste.impl.model.MemoryIDMigrator;  

public
class TestMT { public static void main(String[] args) { // TODO Auto-generated method stub String test = "d140615p10693zc"; MemoryIDMigrator thing2long = new MemoryIDMigrator(); Long testLong = thing2long.toLongID(test); System.out.println(testLong); thing2long.storeMapping(testLong, test); String a =thing2long.toStringID(testLong); System.out
.println(a); } }

MemoryIDMigrator 原始碼

package org.apache.mahout.cf.taste.impl.model;

import java.util.Iterator;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.AbstractIDMigrator;
import org.apache.mahout.cf.taste.model.UpdatableIDMigrator;

public
final class MemoryIDMigrator extends AbstractIDMigrator implements UpdatableIDMigrator { private final FastByIDMap<String> longToString = new FastByIDMap(100); public MemoryIDMigrator() { } public void storeMapping(long longID, String stringID) { FastByIDMap var4 = this.longToString; synchronized(this.longToString) { this.longToString.put(longID, stringID); } } public String toStringID(long longID) { FastByIDMap var3 = this.longToString; synchronized(this.longToString) { return (String)this.longToString.get(longID); } } public void initialize(Iterable<String> stringIDs) { Iterator i$ = stringIDs.iterator(); while(i$.hasNext()) { String stringID = (String)i$.next(); this.storeMapping(this.toLongID(stringID), stringID); } } }

下面是Facebook給出的Mahout協同過濾的測試程式碼

package com.xie;

/**
 * Created by liulu3 on 2017/1/18.
 */
import java.util.ArrayList;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.GenericUserPreferenceArray;
import org.apache.mahout.cf.taste.impl.model.MemoryIDMigrator;
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.recommender.svd.SVDPlusPlusFactorizer;
import org.apache.mahout.cf.taste.impl.recommender.svd.SVDRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;

/**
 * This class shows some examples which are implemented
 * in java for showing how to use the different recommenders
 * in java.
 * It uses animals and foods as examples.
 * @author Manuel Blechschmidt <[email protected]>
 *
 */
public class AnimalFoodRecommender {

    private MemoryIDMigrator id2thing = new MemoryIDMigrator();
    private List<String> foods = new ArrayList<>();
    private List<String> animals = new ArrayList<>();
    private DataModel model;

    private Float[][] preferences = new Float[][]   {
            // Carrots  Grass  Pork Beef    Corn    Fish
            // Rabbit
            new Float[] {10f,  7f, 1f,  2f, null,  1f},
            // Cow
            new Float[] { 7f, 10f, null, null, null, null},
            // Dog
            new Float[] {null,  1f, 10f, 10f, null, null},
            // Pig
            new Float[] { 5f,  6f,  4f, null,  7f,  3f},
            // Chicken
            new Float[] { 7f,  6f,  2f, null, 10f, null},
            // Pinguin
            new Float[] { 2f,  2f, null,  2f,  2f, 10f},
            // Bear
            new Float[] { 2f, null,  8f,  8f,  2f,  7f},
            // Lion
            new Float[] {null, null,  9f, 10f,  2f, null},
            // Tiger
            new Float[] {null, null,  8f, null, null,  5f},
            // Antilope
            new Float[] { 6f, 10f,  1f,  1f, null, null},
            // Wolf
            new Float[] { 1f, null, null,  8f, null,  3f},
            // Sheep
            new Float[] {null,  8f, null, null, null, 2f}
    };


    public AnimalFoodRecommender() {
        initMemoryMigrator();
        initDataModel();
        initRecommender();
    }

    /**
     * This function generates ids for
     * the different things in the demp
     */
    private void initMemoryMigrator() {
        foods.add("Carrots");
        foods.add("Grass");
        foods.add("Pork");
        foods.add("Beef");
        foods.add("Corn");
        foods.add("Fish");
        for(String food : foods) {
            id2thing.storeMapping(id2thing.toLongID(food), food);
            System.out.println(food+" = "+id2thing.toLongID(food));
        }
        animals.add("Rabbit");
        animals.add("Cow");
        animals.add("Dog");
        animals.add("Pig");
        animals.add("Chicken");
        animals.add("Pinguin");
        animals.add("Bear");
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Antilope");
        animals.add("Wolf");
        animals.add("Sheep");
        for(String animal : animals) {
            id2thing.storeMapping(id2thing.toLongID(animal), animal);
            System.out.println(animal+" = "+id2thing.toLongID(animal));
        }
    }

    public void initDataModel() {
        FastByIDMap<PreferenceArray> preferenceMap = new FastByIDMap<>();
        for(int i=0;i<animals.size();i++) {
            List<Preference> userPreferences = new ArrayList<>();
            long userId = id2thing.toLongID(animals.get(i));
            for(int j=0;j<foods.size();j++) {
                if(preferences[i][j] != null) {
                    userPreferences.add(new GenericPreference(userId, id2thing.toLongID(foods.get(j)), preferences[i][j]));
                }
            }
            GenericUserPreferenceArray userArray = new GenericUserPreferenceArray(userPreferences);
            preferenceMap.put(userId, userArray);
        }
        model = new GenericDataModel(preferenceMap);
    }

    public void initRecommender() {
        try {

            PearsonCorrelationSimilarity pearsonSimilarity = new PearsonCorrelationSimilarity(model);

            // Java: Similarity between Wolf and Bear: 0.8196561646738477
            // R: corr(c(8,3,1),c(8,7,2)): 0.8196562
            System.out.println("Similarity between Wolf and Bear: "+pearsonSimilarity
                    .userSimilarity(id2thing.toLongID("Wolf"), id2thing.toLongID("Bear")));
            // Similarity between Wolf and Rabbit: -0.6465846072812313
            // R: cor(c(8,3,1),c(2,1,10)): -0.6465846
            System.out.println("Similarity between Wolf and Rabbit: "+pearsonSimilarity
                    .userSimilarity(id2thing.toLongID("Wolf"), id2thing.toLongID("Rabbit")));
            // Similarity between Wolf and Pinguin: -0.24019223070763077
            // R: cor(c(8,3,1),c(2,10,2)): -0.2401922
            System.out.println("Similarity between Wolf and Pinguin: "+pearsonSimilarity
                    .userSimilarity(id2thing.toLongID("Wolf"), id2thing.toLongID("Pinguin")));

            GenericUserBasedRecommender recommender = new GenericUserBasedRecommender(model,
                    new NearestNUserNeighborhood(3, pearsonSimilarity, model), pearsonSimilarity);
            for(RecommendedItem r : recommender.recommend(id2thing.toLongID("Wolf"), 3)) {
                System.out.println("UserBased: Wolf should eat: "+id2thing.toStringID(r.getItemID())+" Rating: "+r.getValue());
            }
            SVDRecommender svdrecommender = new SVDRecommender(model, new SVDPlusPlusFactorizer(model, 4, 1000));
            for(RecommendedItem r : svdrecommender.recommend(id2thing.toLongID("Sheep"), 3)) {
                System.out.println("SVD: Sheep should eat: "+id2thing.toStringID(r.getItemID())+" Rating: "+ r.getValue());
            }
        } catch (TasteException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new AnimalFoodRecommender();
    }
}

相關推薦

Mahout協同過濾是的ID型別問題

mahout做推薦的輸入只能是long型別,但在某些網站中,儲存的資料不是long型別,是string型別。 現在的手機APP,每個手機都有其device_id,也是string型別。如果能以string型別作為uid,即使使用者不註冊,不登入。只要採用dev

hadoop hdfs+mahout 整合協同過濾時出現的兩個異常記錄

再說異常之前 先將專案的pom檔案配置發一下 <dependencies> <dependency> <groupId>org.apache.mahout</groupId>

使用Mahout實現協同過濾 spark

Mahout使用了Taste來提高協同過濾演算法的實現,它是一個基於Java實現的可擴充套件的,高效的推薦引擎。Taste既實現了最基本的基 於使用者的和基於內容的推薦演算法,同時也提供了擴充套件介面,使使用者可以方便的定義和實現自己的推薦演算法。同時,Taste不僅僅只適用於Java應用程式,它 可以作為

svd 協同過濾

#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 20 21:02:58 2018 @author: luogan """ #coding=UTF-8 from num

【Machine Learning】Mahout基於協同過濾(CF)的使用者推薦

一、Mahout推薦演算法簡介 Mahout演算法框架自帶的推薦器有下面這些: l  GenericUserBasedRecommender:基於使用者的推薦器,使用者數量少時速度快; l  GenericItemBasedRecommender:基於商品推薦器,商品數量

8.7 Mahout協同過濾

mahout是一個工具一個來自Apache的、開源的、JAVA的機器學習軟體庫當所處理的資料規模遠大於單機處理能力時成為一種可選的機 器學習工具,建立在Apache的Hadoop分散式計算專案之上mahout安裝:1,上傳apache-mahout-distribution-

Neo4j 推薦 (12)—— 協同過濾(基於鄰域的推薦)

kNN——K近鄰 現在我們有了一種基於偏好查詢類似使用者的方法,下一步是允許每個k個最相似的使用者投票選擇應該推薦的專案。 主要有:             

Neo4j 推薦 (11)—— 協同過濾(皮爾遜相似性)

皮爾遜相似性或皮爾遜相關性是我們可以使用的另一種相似度量。這特別適合產品推薦,因為它考慮到不同使用者將具有不同的平均評分這一事實:平均而言,一些使用者傾向於給出比其他使用者更高的評分。由於皮爾遜相似性考慮了均值的差異,因此該指標將解釋這些差異。 根據皮爾遜的相似度,找到與Cynthia

Neo4j 推薦 (10)—— 協同過濾(餘弦相似度)

餘弦距離: Jaacard相似度對於比較電影很有用,實際上是比較兩組(型別、演員、導演等)。但是對於電影評級,每個關係都有一個我們可以考慮的權重。 餘弦相似度: 兩個使用者的餘弦相似度將告訴我們兩個使用者對電影的偏好有多相似。具有高餘弦相似度的使用者將具有類似的偏好。 根據

Neo4j 推薦 (9)—— 協同過濾(人群的智慧)

簡單的協同過濾 MATCH (u:User {name: "Cynthia Freeman"})-[:RATED]->(:Movie)<-[:RATED]-(o:User) MATCH (o)-[:RATED]->(rec:Movie) WHERE NOT EXISTS(

Neo4j 推薦 (8)—— 協同過濾(利用電影評級)

協同過濾: 使用網路中其他使用者的首選項,評級和操作來查詢要推薦的專案。 (買這個東西的使用者,還買了那個東西)   使用者Misty Williams的所有評分 // Show all ratings by Misty Williams MATCH (u:User

Neo4j 推薦 (3)—— 協同過濾

協同過濾簡單來說是利用某興趣相投、擁有共同經驗之群體的喜好來推薦使用者感興趣的資訊 MATCH (m:Movie {title: "Crimson Tide"})<-[:RATED]-(u:User)-[:RATED]->(rec:Movie) RETURN rec.title

Spark 協同過濾(CF)如何將一直為Long型別的user轉換為Rating中要求的int型別 (測試通過)

/** * 問題: * 在對資料進行訓練時,Rating要求的是int,int,double,但是現有的資料是long,string,double類 型,使用toInt進行轉換時依然會報錯,這是因為long型別轉換成int型別已經超出了int的最大值。 * * 解決思路:

mahout基於矩陣分解的協同過濾例項 ALS——WR

問題提出:對於協同過濾,我們就是要預測使用者所喜歡的但是又沒有發現的物品,下面給出一個明確的評分矩陣,設為A,但是A有一部分沒有值,表明使用者沒有對此物品評分,於是我們需要預測出沒有值的評分部分。 解決方法: 我們知道有基於使用者和基於物品的協同過濾演算法,

Mahout協同過濾演算法原始碼分析(3)--parallelALS

Mahout版本:0.7,hadoop版本:1.0.4,jdk:1.7.0_25 64bit。接上篇,此篇分析parallelALS的initializeM函式和for迴圈(for迴圈裡面含有一個QR分解,此篇只分析到這裡為止)。parallelALS的原始碼對應為:org.

Mahout基於使用者的協同過濾演算法的例子

每行測試資料分別標識使用者id(uid),物品id(itemid),評分(rating),評分時間(time) 3464,2502,3,973282547 3464,3160,2,973282494 3464,2505,3,967175070 3464,

深入理解mahout基於hadoop的協同過濾流程

mahout版本為mahout-distribution-0.9 mahout基於hadoop協同過濾(itembased)觸發類為org.apache.mahout.cf.taste.hadoop.item.RecommenderJob。 執行RecommenderJob

Mahout系列之推薦演算法-基於物品協同過濾實踐

上文已經說明了使用者的協同過濾,這篇也來談談基於物品的協同過濾。 2.基於物品的協同過濾 類似的,也很容易做出一個簡單的基於物品的過濾方法。 1. 單機基本演算法實踐 public static void ItemBased() {try {//DataModel mo

Mahout系列之推薦演算法-基於使用者協同過濾

Mahout的一大特色就是包含了推薦演算法,裡面包括了多種常見的演算法,下面我們來分析分析。 針對基於使用者行為資料的推薦演算法一般稱為協同過濾演算法。協同過濾演算法有基於領域(neighborhood-based)的方法,隱語義模型(latent factor model

【推薦系統】2017年,你還在用使用者畫像和協同過濾推薦系統嗎?

本文是大資料雜談 7 月 13 日社群公開課分享整理,也是第四正規化主題月的第二堂公開課內容。 今天想和大家分享,如何使用大規模機器學習解決真實的業務問題。我們今天會以機器學習中的一個典型場景為例來講解,即基於大規模機器學習模型的推薦系統。 推薦系統的本質是什麼? 比如說我們看到手機淘寶首頁,往下一