You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Hands-On ML2房屋数据代码遇WinError 10060超时错误求助

问题代码及报错

以下是用于获取《Hands-On Machine Learning 2》房屋数据集的Python代码:

import os
import urllib.request
import tarfile

DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
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()

fetch_housing_data()

import pandas as pd

def load_housing_data(housing_path=HOUSING_PATH):
    csv_path = os.path.join(housing_path,"housing.csv")
    return pd.read_csv(csv_path)

housing = load_housing_data()

运行后出现连接超时错误:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>

解决方法

方法1:手动下载跳过代码获取步骤

  1. 下载房屋数据集的CSV文件(或压缩包)
  2. 在项目目录下创建datasets/housing文件夹,将下载的housing.csv放入该目录
  3. 注释掉fetch_housing_data()调用,直接运行load_housing_data()即可加载数据

方法2:修改代码添加超时与代理(若有可用代理)

替换原fetch_housing_data函数,使用更灵活的requests库(需先执行pip install requests安装),添加超时设置和代理:

import requests
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")
    # 设置10秒超时,若有代理则替换为实际代理地址
    proxies = {"http": "http://你的代理地址:端口", "https": "https://你的代理地址:端口"}
    response = requests.get(housing_url, timeout=10, proxies=proxies)
    with open(tgz_path, "wb") as f:
        f.write(response.content)
    # 解压代码保持不变
    housing_tgz = tarfile.open(tgz_path)
    housing_tgz.extractall(path=housing_path)
    housing_tgz.close()

方法3:替换为国内可访问的数据集链接

将HOUSING_URL替换为国内开源镜像站提供的对应数据集链接,规避GitHub raw链接的访问限制。

内容的提问来源于stack exchange,提问作者Ch Venkatesh66

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:52:39