一个完整的机器学习项目——代码解析(一)

版权声明:转载请联系博主、标明出处 https://blog.csdn.net/jyfbug/article/details/88862409

下载了《机器学习实战:基于Scikit-Learn和TensorFlow》,然后阅读,对里面的代码给出一点注释和解析,从头开始吧!
先学习第一个项目中的第一块(下载数据集):
把自己加注释的代码放上:

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" #文件名

def fetch_housing_data(housing_url = HOUSING_URL,housing_path = HOUSING_PATH):      #默认下载url和存储路径
    if not os.path.isdir(housing_path):   #如果不存在当前路径文件夹
        os.makedirs(housing_path)          #创建路径文件夹
    tgz_path = os.path.join(housing_path,"housing.tgz")   #连接路径,最终tgz_path为"datasets/housing/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")  #连接到csv的路径
    return pd.read_csv(csv_path)      #读取csv文件


下面放上每个函数的作用:

os.path.isdir():  判断某一路径是否为目录
os.makedirs():  用于递归创建目录(可以一次创建多个目录)
os.path.join():  连接两个或更多的路径名组件
urllib.request.urlretrieve(): 将URL表示的网络对象复制到本地文件
tarfile.open()、extractall()、close(): 三个函数配合解压文件
pd.read_csv():  读取csv文件

努力坚持更,希望能写完。。。

猜你喜欢

转载自blog.csdn.net/jyfbug/article/details/88862409