非常快速的方法来读取所有双精度的干净矩阵(此矩阵中没有NA上的缺失元素)。大多数条目是非零双精度,也许 30% 是零。维度约为 100 万行和 100 列。
我正在使用的功能如下。但是,对于超过 1 GB 的矩阵来说,它非常慢。
如何更快地完成此操作?以下任何一项是否有帮助:- 不要另存为 csv 并读取它,请尝试另存为二进制格式或其他格式。- 转置数据文件中的矩阵,然后逐列读取,而不是像下面的函数那样逐行读取。- 以某种方式将矩阵序列化为 Java 对象以进行重新读取。
private static Vector<Vector<Double>> readTXTFile(String csvFileName, int skipRows) throws IOException {
String line = null;
BufferedReader stream = null;
Vector<Vector<Double>> csvData = new Vector<Vector<Double>>();
try {
stream = new BufferedReader(new FileReader(csvFileName));
int count = 0;
while ((line = stream.readLine()) != null) {
count += 1;
if(count <= skipRows) {
continue;
}
String[] splitted = line.split(",");
Vector<Double> dataLine = new Vector<Double>(splitted.length);
for (String data : splitted) {
dataLine.add(Double.valueOf(data));
}
csvData.add(dataLine);
}
} finally {
if (stream != null)
stream.close();
}
return csvData;
}
我更改了您的代码以摆脱所有 Vector 和 Double 对象的创建,转而使用固定大小的矩阵(这确实假设您知道或可以提前计算文件中的行数和列数)。
我向它扔了 500,000 行文件,并看到了大约 25% 的改进。
private static double[][] readTXTFile(String csvFileName, int skipRows) throws IOException {
BufferedReader stream = null;
int totalRows = 500000, totalColumns = 6;
double[][] matrix = new double[totalRows][totalColumns];
try {
stream = new BufferedReader(new FileReader(csvFileName));
for (int currentRow = 0; currentRow < totalRows; currentRow++) {
String line = stream.readLine();
if (currentRow <= skipRows) {
continue;
}
String[] splitted = line.split(",");
for (int currentColumn = 0; currentColumn < totalColumns; currentColumn++) {
matrix[currentRow][currentColumn] = Double.parseDouble(splitted[currentColumn]);
}
}
} finally {
if (stream != null) {
stream.close();
}
}
return matrix;
}