无法重现《Hands-On Machine Learning》Housing数据集的问题求助
Fixing the FileNotFoundError for the Housing Dataset
Hey there! Let's get that Housing dataset loaded properly—your error stems from two easy-to-fix issues:
1. You Haven't Fetched the Data Yet
Your load_housing_data() function is looking for housing.csv, but you never ran the fetch_housing_data() function that downloads and extracts this file from the GitHub repo. That's why the file doesn't exist in your target directory!
2. Your HOUSING_URL Is Invalid
You accidentally appended your local file path to the GitHub download root, creating a broken web address. The correct URL points directly to the housing.tgz file stored in the book's dataset folder, not your local system.
Step-by-Step Fix
First, correct the download URL, then run the fetch function before attempting to load the data:
Corrected Full Code
import os import tarfile from six.moves import urllib import pandas as pd # Fix the download URL to point to the correct dataset location DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/" HOUSING_PATH = "/home/isaac/Fundamentals of Data Science Certificate/3253 - Machine Learning/Code from book" # This is the valid path to the housing.tgz in the GitHub repo HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz" def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH): if not os.path.isdir(housing_path): os.makedirs(housing_path) tgz_path = os.path.join(housing_path, "housing.tgz") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close() def load_housing_data(housing_path=HOUSING_PATH): csv_path = os.path.join(housing_path, "housing.csv") return pd.read_csv(csv_path) # First: Download and extract the dataset (this creates housing.csv) fetch_housing_data() # Now: Load the dataset housing = load_housing_data() housing.head()
Quick Additional Checks
- Verify your
HOUSING_PATHhas write permissions—if you hit a permissions error, switch to a simpler path like"./housing_data"(a folder in your current working directory) to avoid issues with spaces or special characters. - After running
fetch_housing_data(), check your target folder—you should see bothhousing.tgz(the downloaded archive) andhousing.csv(the extracted data file).
内容的提问来源于stack exchange,提问作者Isaac A
相关产品推荐
相关产品推荐

