cqc*_*991 31 python jupyter-notebook
我正在使用Ipython Notebook进行研究.随着我的文件越来越大,我不断提取代码,比如绘图方法,拟合方法等.
我想我需要一种方法来组织这个.有什么好办法吗?
目前,我这样做:
data/
helpers/
my_notebook.ipynb
import_file.py
Run Code Online (Sandbox Code Playgroud)
我在存储数据data/,并提取helper method到helpers/,并分成像文件plot_helper.py,app_helper.py等等.
我总结了进口import_file.py,
from IPython.display import display
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib as mpl
from matplotlib import pyplot as plt
import sklearn
import re
Run Code Online (Sandbox Code Playgroud)
然后我可以.ipynb在顶部单元格中导入我需要的所有内容
该结构可以在https://github.com/cqcn1991/Wind-Speed-Analysis看到
我现在遇到的一个问题是我有太多的子模块helpers/,而且很难想出应该将哪个方法放入哪个文件中.
我认为,一个可行的办法是组织中pre-processing,processing,post-processing.
更新:
我的大型jupyter研究笔记本:https://cdn.rawgit.com/cqcn1991/Wind-Speed-Analysis/master/output_HTML/marham.html
顶部单元格是standard import+ magic+extentions
%matplotlib inline
%load_ext autoreload
%autoreload 2
from __future__ import division
from import_file import *
load_libs()
Run Code Online (Sandbox Code Playgroud)
vol*_*myr 41
有许多方法可以组织ipython研究项目.我正在管理一个由5名数据科学家和3名数据工程师组成的团队,我发现这些技巧对于我们的用例非常有用:
这是我的PyData伦敦演讲的摘要:
http://www.slideshare.net/vladimirkazantsev/clean-code-in-jupyter-notebook
1.创建共享(多项目)utils库
您很可能不得不在不同的研究项目中重复使用/重复某些代码.开始将这些内容重构为"common utils"包.制作setup.py文件,将模块推送到github(或类似),以便团队成员可以从VCS"pip install"它.
放在那里的功能的例子有:
2.将您的胖型笔记本电脑分成较小的笔记本电脑
根据我的经验,带代码(任何语言)的文件长度只有几个屏幕(100-400行).Jupyter Notebook仍然是源文件,但有输出!阅读20多个细胞的笔记本电脑非常困难.我喜欢我的笔记本最多有4-10个单元格.
理想情况下,每个笔记本应该有一个"假设 - 数据 - 结论"三元组.
拆分笔记本的示例:
1_data_preparation.ipynb
2_data_validation.ipynb
3_exploratory_plotting.ipynb
4_simple_linear_model.ipynb
5_hierarchical_model.ipynb
playground.ipynb
将1_data_preparation.ipynb的输出保存到pickle df.to_pickle('clean_data.pkl'),csv或fast DB,并pd.read_pickle("clean_data.pkl")在每个笔记本的顶部使用.
3.它不是Python - 它是IPython Notebook
使笔记本独一无二的是细胞.好好利用它们.每个单元格应该是"idea-execution-output"三元组.如果单元格没有输出任何内容 - 与下面的单元格结合使用.导入单元格应该不输出任何内容 - 这是它的预期输出.
如果单元格的输出很少 - 可能值得拆分它.
隐藏进口可能是也可能不是好主意:
from myimports import *
Run Code Online (Sandbox Code Playgroud)
您的读者可能想弄清楚您要导入的是什么,以便将相同的内容用于她的研究.所以要谨慎使用.但我们确实使用它pandas, numpy, matplotlib, sql.
在/helpers/model.py中隐藏"秘密酱"是不好的:
myutil.fit_model_and_calculate(df)
Run Code Online (Sandbox Code Playgroud)
这可以节省你打字,你会删除重复的代码,但你的合作者将不得不打开另一个文件弄清楚发生了什么事情.不幸的是,笔记本(jupyter)是非常不灵活和基本的环境,但你仍然不想强迫你的读者为每一段代码留下它.我希望将来IDE能够改进,但是现在,在笔记本中保留"秘密酱".而"无聊和明显的工具" - 无论你认为合适的地方.干仍然适用 - 你必须找到平衡.
这不应该阻止您将可重用代码打包到函数甚至小类中.但"扁平比嵌套更好".
4.保持笔记本清洁
您应该能够在任何时间"重置并运行全部".
每次重播都应该快!这意味着您可能需要投资编写一些缓存功能.可能你甚至想把它们放到你的"常用工具"模块中.
每个单元格应该可以执行多次,而无需重新初始化笔记本.这可以节省您的时间并使代码更加健壮.但它可能取决于先前单元格创建的状态.使每个细胞完全独立于上述细胞是一种反模式IMO.
完成研究后 - 你没有完成笔记本电脑.重构.
5.创建一个项目模块,但要非常有选择性
如果您继续使用绘图或分析功能 - 请将其重构为此模块.但根据我的经验,人们希望阅读和理解笔记本,而无需打开多个util子模块.因此,与普通Python相比,在这里命名您的子例程更为重要.
"干净的代码读起来就像写得很好的散文"Grady Booch(UML的开发者)
6.为整个团队托管云中的Jupyter服务器
您将拥有一个环境,因此每个人都可以快速查看和验证研究,而无需匹配环境(即使conda使这非常简单).
您可以默认配置默认值,如mpl样式/颜色和make matplot lib inline:
在 ~/.ipython/profile_default/ipython_config.py
添加行 c.InteractiveShellApp.matplotlib = 'inline'
7.(实验想法)从另一个笔记本运行一个具有不同参数的笔记本
通常,您可能需要重新运行整个笔记本,但使用不同的输入参数.
为此,您可以按如下方式构建研究笔记本:将params字典放在 "源笔记本" 的第一个单元格中.
params = dict(platform='iOS',
start_date='2016-05-01',
retention=7)
df = get_data(params ..)
do_analysis(params ..)
Run Code Online (Sandbox Code Playgroud)
在另一个(更高逻辑级别)笔记本中,使用此函数执行它:
def run_notebook(nbfile, **kwargs):
"""
example:
run_notebook('report.ipynb', platform='google_play', start_date='2016-06-10')
"""
def read_notebook(nbfile):
if not nbfile.endswith('.ipynb'):
nbfile += '.ipynb'
with io.open(nbfile) as f:
nb = nbformat.read(f, as_version=4)
return nb
ip = get_ipython()
gl = ip.ns_table['user_global']
gl['params'] = None
arguments_in_original_state = True
for cell in read_notebook(nbfile).cells:
if cell.cell_type != 'code':
continue
ip.run_cell(cell.source)
if arguments_in_original_state and type(gl['params']) == dict:
gl['params'].update(kwargs)
arguments_in_original_state = False
Run Code Online (Sandbox Code Playgroud)
这种"设计模式"是否有用还有待观察.我们取得了一些成功 - 至少我们停止复制笔记本只是为了改变一些输入.
将笔记本重构为类或模块会破坏单元提供的"idea-execute-output"的快速反馈循环.并且,恕我直言,不是"ipythonic"..
8.在笔记本中对共享库进行写(单元)测试,并使用py.test运行
py.test有一个插件,可以在笔记本中发现和运行测试!
https://pypi.python.org/pypi/pytest-ipynb
虽然给出的答案彻底涵盖了该主题,但仍然值得一提的是Cookiecutter,它提供了数据科学样板项目结构:
\n为 Python 项目提供数据科学模板,具有逻辑合理、标准化但灵活的项目结构,用于执行和共享数据科学工作。
\n您的分析不必使用 Python,但模板确实提供了一些 Python 样板文件(例如在 src 文件夹中,以及 docs 中的 Sphinx 文档框架)。然而,没有任何约束力。
\n下面引用的项目描述很好地总结了这一点:
\n\n\n在创建新的 Rails 项目之前,没有人会坐下来思考\n他们想要将自己的观点放在哪里;他们只是
\nrails new像其他人一样跑去获得一个标准的项目框架。
pip install cookiecutter\n\n启动新项目就像在命令行运行此命令一样简单。无需先创建目录,cookiecutter\n会为您完成此操作。
\n
cookiecutter https://github.com/drivendata/cookiecutter-data-science\nRun Code Online (Sandbox Code Playgroud)\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 LICENSE\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Makefile <- Makefile with commands like `make data` or `make train`\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 README.md <- The top-level README for developers using this project.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 data\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 external <- Data from third party sources.\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 interim <- Intermediate data that has been transformed.\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 processed <- The final, canonical data sets for modeling.\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 raw <- The original, immutable data dump.\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 docs <- A default Sphinx project; see sphinx-doc.org for details\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 models <- Trained and serialized models, model predictions, or model summaries\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),\n\xe2\x94\x82 the creator\'s initials, and a short `-` delimited description, e.g.\n\xe2\x94\x82 `1.0-jqp-initial-data-exploration`.\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 references <- Data dictionaries, manuals, and all other explanatory materials.\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 reports <- Generated analysis as HTML, PDF, LaTeX, etc.\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 figures <- Generated graphics and figures to be used in reporting\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 requirements.txt <- The requirements file for reproducing the analysis environment, e.g.\n\xe2\x94\x82 generated with `pip freeze > requirements.txt`\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 src <- Source code for use in this project.\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py <- Makes src a Python module\n\xe2\x94\x82 \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 data <- Scripts to download or generate data\n\xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 make_dataset.py\n\xe2\x94\x82 \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 features <- Scripts to turn raw data into features for modeling\n\xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 build_features.py\n\xe2\x94\x82 \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 models <- Scripts to train models and then use trained models to make\n\xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x82 predictions\n\xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 predict_model.py\n\xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 train_model.py\n\xe2\x94\x82 \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 visualization <- Scripts to create exploratory and results-oriented visualizations\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 visualize.py\n\xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 tox.ini <- tox file with settings for running tox; see tox.testrun.org\nRun Code Online (Sandbox Code Playgroud)\nProjectTemplate - 为 R 数据分析提供类似的系统。
\n理想情况下,您应该有一个库层次结构。我会将其组织如下:
基本的、最低级别的包[无依赖项]
stringutils.py:包含字符串操作等最基本的文件 dateutils.py:日期操作方法
数学相关的实用程序、模型、PDF、CDF [取决于 wsautils、wsadata] 包含: - Probabilityutils.py - statutils.py 等。
你明白了。根据需要创建更多库,但不要创建太多。
最后,请记住,给猫剥皮的方法有很多种,以上只是我碰巧喜欢的一种。HTH。