《机器学习实战:基于Scikit-Learn和TensorFlow 》笔记

P71代码详解

import os
import tarfile
from six.moves import urllib
import pandas as pd

#下载地址
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
#本地存储地址(本文件夹下)
HOUSING_PATH = "datasets/housing"
HOUSING_URL = DOWNLOAD_ROOT + HOUSING_PATH + "/housing.tgz"
#从外网下载housing.tgz,并解压它为housing.csv
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
	#如果不存在datasets/housing文件夹
	if not os.path.isdir(housing_path):
		#则创建它
		os.makedirs(housing_path)
		#housing.tgz的本地存放地址,join起连接作用,在需要的时候会自动补全'/'
		#补全后tgz_path = datasets/housing/housing.tgz
		tgz_path = os.path.join(housing_path, "housing.tgz")
		#从housing_url下载资源至tgz_path
		urllib.request.urlretrieve(housing_url, tgz_path)
		#打开housing.tgz 并返回给housing_tgz
		housing_tgz = tarfile.open(tgz_path)
		#解压housing_tgz下的所有文件
		housing_tgz.extractall(path=housing_path)
		#关闭文件
		housing_tgz.close()
		
fetch_housing_data()

#读取解压后的housing.csv文件
def load_housing_data(housing_path=HOUSING_PATH):
	csv_path = os.path.join(housing_path, "housing.csv")
	return pd.read_csv(csv_path)

#返回并打印
ans = load_housing_data()
print(ans)

你可能感兴趣的:(机器学习)