如何将 arff 文件转换为矩阵



>我有arff文件需要转换为矩阵。我已经将文件转换为数组,但无法将其转换为矩阵。有人可以帮忙。下面我有用于将数据转换为数组的代码

BufferedReader reader = new BufferedReader(new FileReader("colon.arff"));
       ArffReader arff = new ArffReader(reader);
     Instances data = arff.getData();
     data.setClassIndex(data.numAttributes() - 1);
     for (int i = 0; i < data.numAttributes(); i++)
{
    // Print the current attribute.
    System.out.print(data.attribute(i) + ": ");
    // Print the values associated with the current attribute.
    double[] values = data.attributeToDoubleArray(i);
   //data= new double [row][col];
    System.out.println(Arrays.toString(values));
}

假设你想要一个double[][],请按以下步骤操作:

收集ArrayList<double[]>中的所有double[]

最后,使用 list.toarray(new double[list.size()][]) 或类似方式将动态长度列表转换为固定长度数组。

或者直接分配输出数组,因为Instances已经知道属性和实例的数量。

请注意,严格来说double[][]并不是一个矩阵。它可以是参差不齐的,即行可以有不同的长度。此外,上面的代码将生成一个转置矩阵,可能不是您所期望的。您可能需要循环访问实例并改用instance.toDoubleArray()

无论如何,请查看attributeToDoubleArray的源代码以了解Weka在内部所做的事情,从而为您提供一些如何进行的想法。

最新更新