在 java 中读取 MNIST 数据库非常慢
Reading MNIST database in java very slow
我之前用 C++ 制作了一个 MNIST reader,速度非常快,现在我尝试在 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 个字节并 returns 以 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 中获取一个字节。
我之前用 C++ 制作了一个 MNIST reader,速度非常快,现在我尝试在 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 个字节并 returns 以 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 中获取一个字节。