Mahout之文本向量化

背景:

进行文本挖掘的时候,无论是聚类还是相似计算首先需要向量化。

思路:

对于某一文本计算完其tf(tf-idf)之后生成word->tf(tf-idf)的对应表,那么构造成向量记做:

v=(a1,a2,…,an) 此为为n维向量。a1...an为tf(tf-idf),同时我们把word转换成int来作为下标。

实现:

	/**
	 * vector转换
	 * 
	 * @param map 单词和词频map
	 * @param otherInfo 用于保存的其他信息
	 * @return Vector
	 */
	public static Vector vector(Map<String, Double> map, String otherInfo) {
		Vector vector = new RandomAccessSparseVector(Integer.MAX_VALUE);
		NamedVector nv = new NamedVector(vector, otherInfo);
		Iterator<Entry<String, Double>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Double> entry = iterator.next();
			nv.setQuick(entry.getKey().hashCode(), entry.getValue());
		}
		return vector;
	}

PS:可以根据自己的需要选择相应的Vector实现类.

猜你喜欢

转载自snv.iteye.com/blog/1874179