首页 > 解决方案 > 在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;
}

关于为什么这么慢的任何帮助都会对我有所帮助。我使用了其他人的示例,其中他使用了字节缓冲区并且它工作得很快(大约一秒钟)。

标签: javaruntimemnist

解决方案


你肯定想使用BufferedInputStream这样的:

inputStream = new BufferedInputStream(new FileInputStream(imageFile));

在不缓冲每个调用的情况inputStream.read()下从操作系统获取一个字节。


推荐阅读