加载MNIST数据集触发FileNotFoundError:文件或目录不存在
Hey there, let's work through this FileNotFoundError you're hitting when trying to load the MNIST dataset with mnist_loader.py. The error is clear: Python can't locate the ../data/mnist.pkl file, so we'll walk through the most common fixes below:
1. Verify the MNIST data file exists
First, double-check if you actually have the mnist.pkl file in the expected location:
- Look for a
datadirectory that's one level above where yourmnist_loader.pyis saved. If that directory doesn't exist, or it's missingmnist.pkl, you'll need to get the file first. - The tutorial's official code repository includes this data file—you can locate the
datafolder in the repo and downloadmnist.pkldirectly.
2. Correct the file path
If you already have mnist.pkl but the path is misaligned, try these adjustments:
- Use an absolute path: Open
mnist_loader.pyand find the line where it loadsmnist.pkl(usually in theload_datafunction). Replace the relative path../data/mnist.pklwith the full absolute path to your file. For example:# Replace this line f = open('../data/mnist.pkl', 'rb') # With something like this (adjust to your actual file path) f = open('C:/Users/Joseph Gannon/data/mnist.pkl', 'rb') - Fix the folder structure: Ensure your directory setup matches what the script expects. If
mnist_loader.pyis inC:/Users/Joseph Gannon/Projects/nn/, then../data/mnist.pklpoints toC:/Users/Joseph Gannon/data/mnist.pkl. Create thatdatafolder in your user directory and placemnist.pklinside it.
3. Check your working directory
Sometimes the issue is that you're running the script from a different directory than where mnist_loader.py lives. To confirm, run this code before loading the data:
import os print(os.getcwd())
This will show you your current working directory. Make sure the relative path ../data/mnist.pkl makes sense from this location. If not, either change your working directory to match the script's location, or adjust the path in mnist_loader.py.
4. Redownload the data (if corrupted or missing)
If you suspect mnist.pkl is corrupted or you never downloaded it, grab a fresh copy from the tutorial's code repo. Some versions of mnist_loader.py include automatic download logic, but if yours doesn't, manually placing the file in the correct path will resolve the error.
内容的提问来源于stack exchange,提问作者Gonge

