稳定输出加速开发:数据科学项目开始时应该包括的7个设置

开发 前端
在开始一项数据科学项目时,我们通常需要进行设置或配置,以确保所需的依赖关系,保持输出稳定,准备通用函数。本文将介绍JuypterNotebook中最有帮助的一些项目设置。

本文转载自公众号“读芯术”(ID:AI_Discovery)。

在开始一项数据科学项目时,我们通常需要进行设置或配置,以确保所需的依赖关系,保持输出稳定,准备通用函数。

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

项目设置的一个案例(来自Handson-ML2)

本文将介绍JuypterNotebook中最有帮助的一些项目设置。

1. 确保Python版本

检查JupyterNotebook中的Python解释器版本:

  1. import sys 
  2. sys.version'3.7.6 (default, Jan 8 2020, 13:42:34) \n[Clang 4.0.1 (tags/RELEASE_401/final)]' 

为确保项目由Python解释器的最低及以上要求版本运行,可在项目设置中添加以下代码:

  1. # Python ≥3.7 is required 
  2. import sys 
  3. assert sys.version_info >= (3, 7) 

Python需要为3.7及以上版本,否则会抛出AssertionError。

2. 确保程序包版本

检查安装的程序包版本,如TensorFlow。

  1. import tensorflow as tf 
  2. tf.__version__'2.0.0' 

确保项目是由TensorFlow2.0及以上版本运行的,否则会抛出AssertionError。

  1. # TensorFlow ≥2.0 is required 
  2. import tensorflow as tf 
  3. assert tf.__version__ >= "2.0" 

3. 避免绘制模糊图像

JuypterNotebook中的默认绘图看起来有些模糊。例如,一张查找缺失值的简单热图。

(https://towardsdatascience.com/using-pandas-pipe-function-to-improve-code-readability-96d66abfaf8)

  1. import seaborn as sns 
  2. import matplotlib.pyplot as plt 
  3. %matplotlib inline# Default figure format png 
  4. sns.heatmap(df.isnull(), 
  5.             yticklabels=False
  6.             cbar=False
  7.             cmap='viridis'

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

默认图像看起来很模糊

由上图可以看出,文本很模糊,Cabin栏中的缺失值过于拥挤,Embarked栏中的缺失值无法识别。

要解决这个问题,可在%matplotlib inline之后使用%config InlineBackend.figure_format='retina'或 %configInlineBackend.figure_format = 'svg',即:

  1. %matplotlib inline 
  2. %config InlineBackend.figure_format = 'retina'         # or 'svg'sns.heatmap(df.isnull(), 
  3.             yticklabels=False
  4.             cbar=False
  5.             cmap='viridis'

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

图片格式设置为retina或svg

与先前的图片比较,上图更加清晰,Embarked栏中的缺失值也能成功识别。

4. 在不同运行中保持输出稳定

数据科学项目中很多地方都在使用随机数字。例如:

  • 来自Scikit-Learn的 train_test_split()
  • 用于初始化权重的np.random.rand()

若未重置随机种子,则每次调用都会出现不同的数字:

  1. >>> np.random.rand(4) 
  2. array([0.83209492, 0.10917076, 0.15798519, 0.99356723]) 
  3. >>> np.random.rand(4) 
  4. array([0.46183001, 0.7523687 , 0.96599624, 0.32349079]) 

np.random.seed(0)使随机数字可预测:

  1. >>> np.random.seed(0) 
  2. >>> np.random.rand(4) 
  3. array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) 
  4. >>> np.random.seed(0) 
  5. >>> np.random.rand(4) 
  6. array([0.5488135 , 0.71518937, 0.60276338, 0.54488318]) 

如果(每次)都重置随机种子,那么每次都会出现相同的数据组。因此,项目能在不同运行中保持输出稳定。

5. 多单元输出

默认情况下,JupyterNotebook不能在同一单元中输出多种结果。要输出多种结果,可使用IPython重新配置shell。

  1. from IPython.core.interactiveshell import InteractiveShell 
  2. InteractiveShell.ast_node_interactivity = "all" 

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

6. 将图片保存到文件

Matplotlib能通过savefig()方法保存图片,但如果给定路径不存在则会引发错误。

  1. plt.savefig('./figures/my_plot.png')FileNotFoundError: [Errno 2] Nosuch file or directory: './figures/my_plot.png' 

最好的做法是将所有图片都放到一个地方,如工作区的figures文件夹。可使用OS GUI(操作系统界面)或是在JupyterNotebook中运行logic指令,来手动创建一个figures文件夹,但是最好创建一个小函数来实现该操作。

当需要一些自定义图形设置或附加子文件夹来分组图形时,这种方法尤其适用。以下是将图片保存到文件的函数:

  1. import os 
  2. %matplotlib inline 
  3. import matplotlib.pyplot as plt# Where to save the figures 
  4. PROJECT_ROOT_DIR = "." 
  5. SUB_FOLDER = "sub_folder"    #a sub-folder 
  6. IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", SUB_FOLDER)defsave_fig(name, images_path=IMAGES_PATHtight_layout=True,extension="png"resolution=300): 
  7.     if not os.path.isdir(images_path): 
  8.         os.makedirs(images_path) 
  9.     path = os.path.join(images_path, name+ "." + extension) 
  10.     print("Saving figure:",name) 
  11.     if tight_layout: 
  12.         plt.tight_layout() 
  13.     plt.savefig(path, format=extension,dpi=resolution

现在调用save_fig('figure_name'),会在工作区中创建一个images/sub_folder目录,图片以“figure_name.png”名称被保存到目录中。此外,还提供了三个最常用的设置:

  • tight_layout 能自动调整子图填充
  • extension 能以多种格式保存图片
  • resolution 可设置图片分辨率

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

稳定输出加速开发:数据科学项目开始时应该包括的7个设置

7. 下载数据(并解压)

处理网络数据对于数据科学工作者是常事。可以使用浏览器下载数据,并运行指令来解压文件,但最好的是创建一个小函数来执行该操作。当数据需要定期更改时,这一点尤其重要。

编写一个小脚本,在获取最新数据时运行(也可以设置一个定期自动执行的计划工作)即可。如果需要在多台机器上安装数据集,自动化抓取数据流程也十分有用。

以下是下载并解压数据的函数:

  1. import os 
  2. import tarfile 
  3. import zipfile 
  4. import urllib 
  5.   
  6. # Where to save the data 
  7. PROJECT_ROOT_DIR = "." 
  8. SUB_FOLDER = "group_name" 
  9. LOCAL_PATH = os.path.join(PROJECT_ROOT_DIR, "datasets", SUB_FOLDER)defdownload(file_url, local_path = LOCAL_PATH): 
  10.     if not os.path.isdir(local_path): 
  11.         os.makedirs(local_path) 
  12.         
  13.     # Download file 
  14.     print(">>>downloading") 
  15.     filename = os.path.basename(file_url) 
  16.     file_local_path =os.path.join(local_path, filename) 
  17.     urllib.request.urlretrieve(file_url,file_local_path) 
  18.     
  19.     # untar/unzip file 
  20.     if filename.endswith("tgz")or filename.endswith("tar.gz"): 
  21.         print(">>>unpacking file:", filename) 
  22.         tar =tarfile.open(file_local_path, "r:gz") 
  23.         tar.extractall(path = local_path
  24.         tar.close() 
  25.     eliffilename.endswith("tar"): 
  26.         print(">>> unpackingfile:", filename) 
  27.         tar =tarfile.open(file_local_path, "r:") 
  28.         tar.extractall(path = local_path
  29.         tar.close() 
  30.     eliffilename.endwith("zip"): 
  31.         print(">>>unpacking file:", filename) 
  32.         zip_file = zipfile.ZipFile(file_local_path) 
  33.         zip_file.extractall(path =local_path
  34.         zip_file.close() 
  35.     print("Done") 

现在调用download("http://a_valid_url/housing.tgz"),会在工作区创建一个datasets/group_name目录,下载housing.tgz,并从该目录中提取出housing.csv ,这个小函数也能用于CSV和文本文件。

[[337548]]

图源:unsplash

请查看笔者Github库中的源代码:

https://github.com/BindiChen/machine-learning/blob/master/data-analysis/004-7-setups-for-a-data-science-project/7-setups.ipynb

 

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2019-12-03 09:11:57

数据科学编程算法

2012-11-13 10:34:03

PythonWeb

2012-09-10 10:26:22

工作工作习惯调整心态

2021-01-29 14:38:36

数据科学数据科学家统计学

2019-10-14 15:41:37

数据科学GitHub机器学习

2021-02-20 21:29:40

GitHub代码开发者

2021-04-06 08:00:00

数据湖存储技术

2020-09-17 14:20:24

数据科学简历岗位

2019-12-19 14:42:40

开源数据科学项目

2021-06-29 10:03:45

数据科学机器学习算法

2019-07-03 15:21:47

数据科学统计数据数据结构

2019-08-07 18:52:40

GPU数据科学CPU

2017-09-11 15:46:36

数据科学语言Java

2018-04-09 11:20:40

数据科学项目数据

2017-09-18 10:36:35

Python类库开发者

2013-07-04 13:19:24

Java开发速度

2019-10-22 08:00:22

数据科学AWSDC

2021-09-13 13:43:43

图数据科学

2019-07-11 12:59:27

数据科学家概率分布统计

2015-09-01 16:27:31

薪资错误
点赞
收藏

51CTO技术栈公众号