阅读MNIST数据库

5

我目前正在探索神经网络和机器学习,并在c#中实现了一个基本的神经网络。现在,我想使用MNIST数据库测试我的反向传播训练算法。但是,我读取文件时遇到了严重的问题。

代码当前性能非常糟糕。我目前的目标是掌握这个主题,并获得结构化的视图,了解事物是如何工作的,然后再开始选择更快的数据结构。

为了训练网络,我想要提供一个自定义的TrainingSet数据结构:

[Serializable]
public class TrainingSet
{
    public Dictionary<List<double>, List<double>> data = new Dictionary<List<double>, List<double>>();
}

Keys将是我的输入数据(每个条目(图像)有784个像素,表示0到1范围内的灰度值)。值将是我的输出数据(10个条目,表示从0到9的数字,所有条目都为0,除了期望为1的那个)

现在我想按照这个协议读取MNIST数据库。我目前正在尝试第二次,受到此博客文章的启发:https://jamesmccaffrey.wordpress.com/2013/11/23/reading-the-mnist-data-set-with-c/。不幸的是,它仍然产生与我的第一次尝试相同的无意义结果,将像素散布在奇怪的模式中:Pattern screenshot

我的当前读取算法:

    public static TrainingSet GenerateTrainingSet(FileInfo imagesFile, FileInfo labelsFile)
    {
        MnistImageView imageView = new MnistImageView();
        imageView.Show();

        TrainingSet trainingSet = new TrainingSet();

        List<List<double>> labels = new List<List<double>>();
        List<List<double>> images = new List<List<double>>();

        using (BinaryReader brLabels = new BinaryReader(new FileStream(labelsFile.FullName, FileMode.Open)))
        {
            using (BinaryReader brImages = new BinaryReader(new FileStream(imagesFile.FullName, FileMode.Open)))
            {
                int magic1 = brImages.ReadBigInt32(); //Reading as BigEndian
                int numImages = brImages.ReadBigInt32();
                int numRows = brImages.ReadBigInt32();
                int numCols = brImages.ReadBigInt32();

                int magic2 = brLabels.ReadBigInt32();
                int numLabels = brLabels.ReadBigInt32();

                byte[] pixels = new byte[numRows * numCols];

                // each image
                for (int imageCounter = 0; imageCounter < numImages; imageCounter++)
                {
                    List<double> imageInput = new List<double>();
                    List<double> exspectedOutput = new List<double>();

                    for (int i = 0; i < 10; i++) //generate empty exspected output
                        exspectedOutput.Add(0);

                    //read image
                    for (int p = 0; p < pixels.Length; p++)
                    {
                        byte b = brImages.ReadByte();
                        pixels[p] = b;

                        imageInput.Add(b / 255.0f); //scale in 0 to 1 range
                    }

                    //read label
                    byte lbl = brLabels.ReadByte();
                    exspectedOutput[lbl] = 1; //modify exspected output

                    labels.Add(exspectedOutput);
                    images.Add(imageInput);

                    //Debug view showing parsed image.......................
                    Bitmap image = new Bitmap(numCols, numRows);

                    for (int y = 0; y < numRows; y++)
                    {
                        for (int x = 0; x < numCols; x++)
                        {
                            image.SetPixel(x, y, Color.FromArgb(255 - pixels[x * y], 255 - pixels[x * y], 255 - pixels[x * y])); //invert colors to have 0,0,0 be white as specified by mnist
                        }
                    }

                    imageView.SetImage(image);
                    imageView.Refresh();
                    //.......................................................
                }

                brImages.Close();
                brLabels.Close();
            }
        }

        for (int i = 0; i < images.Count; i++)
        {
            trainingSet.data.Add(images[i], labels[i]);
        }

        return trainingSet;
    }

所有图像都会产生如上所示的图案。虽然它们不是完全相同的图案,但总是似乎将像素“拉”到右下角。


1
pixels[x * y] should probably be pixels[(y * numCols) + x] - Rup
那就是错误了,非常感谢。没有数学的干扰,什么样的项目才是好项目呢? - Robin B
2个回答

14
这是我做的方式:
public static class MnistReader
{
    private const string TrainImages = "mnist/train-images.idx3-ubyte";
    private const string TrainLabels = "mnist/train-labels.idx1-ubyte";
    private const string TestImages = "mnist/t10k-images.idx3-ubyte";
    private const string TestLabels = "mnist/t10k-labels.idx1-ubyte";

    public static IEnumerable<Image> ReadTrainingData()
    {
        foreach (var item in Read(TrainImages, TrainLabels))
        {
            yield return item;
        }
    }

    public static IEnumerable<Image> ReadTestData()
    {
        foreach (var item in Read(TestImages, TestLabels))
        {
            yield return item;
        }
    }

    private static IEnumerable<Image> Read(string imagesPath, string labelsPath)
    {
        BinaryReader labels = new BinaryReader(new FileStream(labelsPath, FileMode.Open));
        BinaryReader images = new BinaryReader(new FileStream(imagesPath, FileMode.Open));

        int magicNumber = images.ReadBigInt32();
        int numberOfImages = images.ReadBigInt32();
        int width = images.ReadBigInt32();
        int height = images.ReadBigInt32();

        int magicLabel = labels.ReadBigInt32();
        int numberOfLabels = labels.ReadBigInt32();

        for (int i = 0; i < numberOfImages; i++)
        {
            var bytes = images.ReadBytes(width * height);
            var arr = new byte[height, width];

            arr.ForEach((j,k) => arr[j, k] = bytes[j * height + k]);

            yield return new Image()
            {
                Data = arr,
                Label = labels.ReadByte()
            };
        }
    }
}

Image类:

public class Image
{
    public byte Label { get; set; }
    public byte[,] Data { get; set; }
}

一些扩展方法:

public static class Extensions
{
    public static int ReadBigInt32(this BinaryReader br)
    {
        var bytes = br.ReadBytes(sizeof(Int32));
        if (BitConverter.IsLittleEndian) Array.Reverse(bytes);
        return BitConverter.ToInt32(bytes, 0);
    }

    public static void ForEach<T>(this T[,] source, Action<int, int> action)
    {
        for (int w = 0; w < source.GetLength(0); w++)
        {
            for (int h = 0; h < source.GetLength(1); h++)
            {
                action(w, h);
            }
        }
    }
}

使用方法:

foreach (var image in MnistReader.ReadTrainingData())
{
    //use image here     
}

或者

foreach (var image in MnistReader.ReadTestData())
{
    //use image here     
}

这里的原始文件(http://yann.lecun.com/exdb/mnist/)是`.gz`文件。您是否对它们进行了修改或直接从中读取? - kaushalpranav
@kaushalpranav 我相信我已经解压缩了它们。 - koryakinp
ReadBigInt32和默认的ReadInt32有什么区别? - blenderfreaky
@blenderfreaky 这些字节是以“高位优先”编码的,因此如果您使用的是英特尔处理器,则需要将其反转;ReadBigInt32正在检查并反转这些字节。 - Domenico Rotolo
@DomenicoRotolo,BinaryReader.ReadInt32/BitConverter.ToInt32 默认情况下不会执行此操作吗? - blenderfreaky
根据维基上的说法: “数组中字节的顺序必须反映计算机系统体系结构的字节序” 所以我想不行。 - Domenico Rotolo

4
为什么不使用nuget包:
  • MNIST.IO 只是一个数据读取器(免责声明:这是我的包)
  • Accord.DataSets 包含了下载和解析机器学习数据集(如MNIST,News20,Iris)的类。此包是Accord.NET框架的一部分。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接