Java 大数据集上具有k均值的堆外内存

Java 大数据集上具有k均值的堆外内存,java,out-of-memory,k-means,Java,Out Of Memory,K Means,我使用k-means算法进行数据聚类,并使用大型数据集。我有将近100000篇研究论文,我想用k-means对它们进行聚类。我使用传统的k-均值,也使用反向索引,但在这两个程序中。当我输入50000时,我将从Java中的堆内存中取出(使用NetBeans) 代码: import java.util.*; 导入java.io.*; 公共类kmeans { 公共静态void main(字符串[]args)引发IOException { //从与kmeans.java相同的文件夹中的所有.txt文件读

我使用k-means算法进行数据聚类,并使用大型数据集。我有将近100000篇研究论文,我想用k-means对它们进行聚类。我使用传统的k-均值,也使用反向索引,但在这两个程序中。当我输入50000时,我将从Java中的堆内存中取出(使用NetBeans)

代码:

import java.util.*;
导入java.io.*;
公共类kmeans
{
公共静态void main(字符串[]args)引发IOException
{
//从与kmeans.java相同的文件夹中的所有.txt文件读入文档
//保存文档(字符串[])及其文件名的并行列表,并创建单词的全局集合列表
ArrayList docs=新建ArrayList();
ArrayList文件名=新的ArrayList();
ArrayList全局=新的ArrayList();
文件夹=新文件(“.”);
List files=Arrays.asList(folder.listFiles)(新文件过滤器(){
公共布尔接受(文件f){
返回f.isFile()和&f.getName().endsWith(“.txt”);
}
}));
BufferedReader in=null;
用于(文件f:文件){
in=新的BufferedReader(新的文件读取器(f));
StringBuffer sb=新的StringBuffer();
字符串s=null;
while((s=in.readLine())!=空){
某人追加;
}
//输入清理正则表达式
字符串[]d=sb.toString().replaceAll(“[\\W&&[^\\s]]”,“”)。拆分(\\W+”;
用于(字符串u:d)
如果(!global.contains(u))
加上(u);
文件.添加(d);
添加(f.getName());
}
//
//计算tf idf并创建文档向量(双[])
ArrayList vecspace=新的ArrayList();
对于(字符串[]s:docs){
double[]d=新的double[global.size()];

对于(int i=0;i您可以使用-Xmx…作为java.exe的命令行参数来增加堆内存量;例如,-Xmx1024m将最大堆大小设置为1024Mb。

您更愿意使用Lucene索引并使用TermFreqs和TermFreqVectors,并从索引计算余弦相似性。这将减少处理时间和内存问题。你应该试一试。

你描述了一个问题,但问题是什么?100000*700(平均字长)*5(平均字长)*32(unicode 32)仅字符串为~=10 GB。这当然不包括存储的不同单词的7000000个对象的开销。必须进行一些优化,这可能还不够(可能需要一个群集)100000*700(纸张的平均长度)*5(关于单词的平均长度)*4(unicode 32)~=2.5 GB
import java.util.*;
import java.io.*;
public class kmeans
{
    public static void main(String[]args) throws IOException
    {
        //read in documents from all .txt files in same folder as kmeans.java
        //save parallel lists of documents (String[]) and their filenames, and create global set list of words
        ArrayList<String[]> docs = new ArrayList<String[]>();
        ArrayList<String> filenames = new ArrayList<String>();
        ArrayList<String> global = new ArrayList<String>();
        File folder = new File(".");
        List<File> files = Arrays.asList(folder.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile() && f.getName().endsWith(".txt");
            }
        }));
        BufferedReader in = null;
        for(File f:files){
            in = new BufferedReader(new FileReader(f));
            StringBuffer sb = new StringBuffer();
            String s = null;
            while((s = in.readLine()) != null){
                sb.append(s);
            }
            //input cleaning regex
            String[] d = sb.toString().replaceAll("[\\W&&[^\\s]]","").split("\\W+");
            for(String u:d)
                if(!global.contains(u))
                    global.add(u);
            docs.add(d);
            filenames.add(f.getName());
        }
        //

        //compute tf-idf and create document vectors (double[])
        ArrayList<double[]> vecspace = new ArrayList<double[]>();
        for(String[] s:docs){
            double[] d = new double[global.size()];
            for(int i=0;i<global.size();i++)
                d[i] = tf(s,global.get(i)) * idf(docs,global.get(i));
            vecspace.add(d);
        }

        //iterate k-means
        HashMap<double[],TreeSet<Integer>> clusters = new HashMap<double[],TreeSet<Integer>>();
        HashMap<double[],TreeSet<Integer>> step = new HashMap<double[],TreeSet<Integer>>();
        HashSet<Integer> rand = new HashSet<Integer>();
        TreeMap<Double,HashMap<double[],TreeSet<Integer>>> errorsums = new TreeMap<Double,HashMap<double[],TreeSet<Integer>>>();
        int k = 3;
        int maxiter = 500;
        for(int init=0;init<100;init++){
            clusters.clear();
            step.clear();
            rand.clear();
            //randomly initialize cluster centers
            while(rand.size()< k)
                rand.add((int)(Math.random()*vecspace.size()));
            for(int r:rand){
                double[] temp = new double[vecspace.get(r).length];
                System.arraycopy(vecspace.get(r),0,temp,0,temp.length);
                step.put(temp,new TreeSet<Integer>());
            }
            boolean go = true;
            int iter = 0;
            while(go){
                clusters = new HashMap<double[],TreeSet<Integer>>(step);
                //cluster assignment step
                for(int i=0;i<vecspace.size();i++){
                    double[] cent = null;
                    double sim = 0;
                    for(double[] c:clusters.keySet()){
                        double csim = cosSim(vecspace.get(i),c);
                        if(csim > sim){
                            sim = csim;
                            cent = c;
                        }
                    }
                    clusters.get(cent).add(i);
                }
                //centroid update step
                step.clear();
                for(double[] cent:clusters.keySet()){
                    double[] updatec = new double[cent.length];
                    for(int d:clusters.get(cent)){
                        double[] doc = vecspace.get(d);
                        for(int i=0;i<updatec.length;i++)
                            updatec[i]+=doc[i];
                    }
                    for(int i=0;i<updatec.length;i++)
                        updatec[i]/=clusters.get(cent).size();
                    step.put(updatec,new TreeSet<Integer>());
                }
                //check break conditions
                String oldcent="", newcent="";
                for(double[] x:clusters.keySet())
                    oldcent+=Arrays.toString(x);
                for(double[] x:step.keySet())
                    newcent+=Arrays.toString(x);
                if(oldcent.equals(newcent)) go = false;
                if(++iter >= maxiter) go = false;
            }
            System.out.println(clusters.toString().replaceAll("\\[[\\w@]+=",""));
            if(iter<maxiter)
                System.out.println("Converged in "+iter+" steps.");
            else System.out.println("Stopped after "+maxiter+" iterations.");
            System.out.println("");

            //calculate similarity sum and map it to the clustering
            double sumsim = 0;
            for(double[] c:clusters.keySet()){
                    TreeSet<Integer> cl = clusters.get(c);
                    for(int vi:cl){
                        sumsim+=cosSim(c,vecspace.get(vi));
                    }
                }
            errorsums.put(sumsim,new HashMap<double[],TreeSet<Integer>>(clusters));

        }
        //pick the clustering with the maximum similarity sum and print the filenames and indices
        System.out.println("Best Convergence:");
        System.out.println(errorsums.get(errorsums.lastKey()).toString().replaceAll("\\[[\\w@]+=",""));
        System.out.print("{");
        for(double[] cent:errorsums.get(errorsums.lastKey()).keySet()){
            System.out.print("[");
            for(int pts:errorsums.get(errorsums.lastKey()).get(cent)){
                System.out.print(filenames.get(pts).substring(0,filenames.get(pts).lastIndexOf(".txt"))+", ");
            }
            System.out.print("\b\b], ");
        }
        System.out.println("\b\b}");
    }

    static double cosSim(double[] a, double[] b){
        double dotp=0, maga=0, magb=0;
        for(int i=0;i<a.length;i++){
            dotp+=a[i]*b[i];
            maga+=Math.pow(a[i],2);
            magb+=Math.pow(b[i],2);
        }
        maga = Math.sqrt(maga);
        magb = Math.sqrt(magb);
        double d = dotp / (maga * magb);
        return d==Double.NaN?0:d;
    }

    static double tf(String[] doc, String term){
        double n = 0;
        for(String s:doc)
            if(s.equalsIgnoreCase(term))
                n++;
        return n/doc.length;
    }

    static double idf(ArrayList<String[]> docs, String term){
        double n = 0;
        for(String[] x:docs)
            for(String s:x)
                if(s.equalsIgnoreCase(term)){
                    n++;
                    break;
                }
        return Math.log(docs.size()/n);
    }
}