gpt4 book ai didi

java - 读取 double 矩阵的有效方法

转载 作者:行者123 更新时间:2023-11-29 05:30:58 25 4
gpt4 key购买 nike

什么是读取所有 double 矩阵的非常快速的方法(该矩阵中没有 NA 上的缺失元素)。大多数条目都是非零 double ,可能 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;
}

关于java - 读取 double 矩阵的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com