我以前用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()
从OS提取单个字节。关于java - 在Java中读取MNIST数据库非常慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54962700/