java - 在java中读取MNIST数据库非常慢
问题描述
我之前用 c++ 制作了一个 MNIST 阅读器,速度非常快,现在我尝试用 Java 重新创建它,但是从数据集中读取标签和图像大约需要 10 秒,这太长了。我对 Java IO 不太了解,所以我不知道我在做什么让它变得如此缓慢。
这是我的代码
public static double[][] loadImages(File imageFile) {
try {
inputStream = new FileInputStream(imageFile);
//Skip Magic number
inputStream.skip(4);
//Read Image Number
int imageNum = nextNByte(4);
//Get Image dimensions
int rows = nextNByte(4);
int cols = nextNByte(4);
//Initialize the image array
double[][] images = new double[imageNum][rows*cols];
//Place the input
for(int i = 0; i<imageNum;i++){
for(int k = 0; k<cols*rows;k++){
images[i][k]= nextNByte(1);
}
}
//Close Input Stream
inputStream.close();
//Verbose Output
System.out.println("Images Loaded!");
return images;
} catch (IOException e) {
e.getCause();
}
//Verbose Output
System.out.println("Couldn't Load Images!");
return null;
}
那是我的图像文件,标签使用相同的方法,所以我不会放上去。这是我为此制作的一个实用函数,它读取 N 个字节并将其以 int 形式返回。
private static int nextNByte(int n) throws IOException {
int k=inputStream.read()<<((n-1)*8);
for(int i =n-2;i>=0;i--){
k+=inputStream.read()<<(i*8);
}
return k;
}
关于为什么这么慢的任何帮助都会对我有所帮助。我使用了其他人的示例,其中他使用了字节缓冲区并且它工作得很快(大约一秒钟)。
解决方案
你肯定想使用BufferedInputStream
这样的:
inputStream = new BufferedInputStream(new FileInputStream(imageFile));
在不缓冲每个调用的情况inputStream.read()
下从操作系统获取一个字节。
推荐阅读
- php - 图像在浏览器中可见,但仍报告为 404
- .net - 如何更新 datagridview 中的特定行和特定列
- arduino - Arduino NodeMCU - ESP8266 - 触摸屏
- matlab - MATLAB中的符号变量是什么?它们与通常使用的变量有何不同?
- javascript - 获得独立于操作系统的实际时间
- html - 如何仅使用 css 重现duckduckgo 搜索的图片库效果
- javascript - 我可以通过哪种方式在 OpenLayers 6 中实现风层?
- javascript - 我们可以在 vercel 中部署 Nextjs 应用程序进行生产吗?它可以处理大流量吗?
- java - 使用 java 从 mongoDb 中删除嵌入的文档
- c# - 针对子集合的流利验证 - 如何在 MVC 中显示错误消息