原标题:Jupyter Notebook的叁大短板,都被这些新工具补齐了
Jupyter Notebook,
从前又称为IPython notebook,是贰个交互式台式机, 协助运维40+种编制程序语言.
能够用来编排美貌的交互式文书档案.
ipython 是 jupyter
notebook的前身并有所ipython的百分百作用
夏乙 发自 凹非寺
Linux下, Jupyter
Notebook的装置进度能够参照Jupyter官方网站,
具体的, 恐怕只需求一句话就能化解:
图片.png
在机器学习和数码正确领域,Jupyter已经家喻户晓。它把笔记、代码、图表、注释融入在贰个交互式的台式机里,还是能增多各类扩充作用。可谓机器学习入门进阶商量之神器。
pip install jupyter
Jupyter Notebook(从前被叫做 IPython
notebook)是三个交互式台式机,帮忙运营 40 两种编制程序语言。Jupyter
Notebook 的原形是3个 Web
应用程序,便于成立和共享经济学化程序文书档案,支持实时期码,数学方程,可视化和
markdown。
用途包涵:数据清理和转移,数值模拟,总计建立模型,机器学习等等Jupyter
Notebook(从前被称之为 IPython notebook)是二个交互式台式机,帮助运营 40
二种编制程序语言。Jupyter Notebook 的精神是三个 Web
应用程序,便于创制和共享文学化程序文书档案,帮忙实时代码,数学方程,可视化和
markdown。 用途包罗:数据清理和转移,数值模拟,总计建立模型,机器学习等等.
jupyter具有 cell,
markdown 整合的成效, 能同时运转代码, 而且是多组的.
同时也能够插入markdown那种多职能注释 包涵图形(但辅助很差).
安装完事后,
在顶峰运转 jupyter notebook
就能够打开jupyter notebook. 先看三个用jupyter notebook的例子(图一),
有个直观的记念:
-
知乎:为何用Jupyter
Notebook -
前几日发觉Jupyter
Notebook比较好用交互式台式机,小编感到笔者从此会时时用到.
1 . Jupyter
Notebook官网
2 .
markdown好用的手册
叁 . 安装步骤参照官方网站步骤
4 . Jupyter
Notebook加多目录 -
起步Jupyter Notebook
后,发现浏览器打开的是暗许文件路线,那样会把计算机多数文书夹都加载上去了,假设要新建三个干净的文本管理,那样操作:
一 . command + shift + G前去文件夹: /Users/zh/.jupyter/
2 . 打开jupyter_notebook_config.py配置文件
3 . command + F 查找 : c.NotebookApp.notebook_dir
4 . 等号后边修改你协调管理的文本路线 -
在Jupyter
Notebook写好之后,再github上新建多少个库房,将自个儿的本地Jupyter
Notebook写的.ipynb文件上传上去就好了 -
终极将自个儿的github地址复制到nbviewer上点击GO,你的对外分享地址就生成了.
-
初体验:请戳我
写教程,写博客非凡一级.
而且还足以上传到jupyterhub…据他们说要和谐搭建
可是,神器也有短板:
- 文本是一向的JSON格式,体量还特别大;
- 要在浏览器里编辑文书档案好烦,好挂念自身喜爱的编辑器;
- 版本调控好困难,想用标准的联合工具来同盟,不过人家只扶助文件!
图1 一个Jupyter Notebook
图片.png
对此初学者的话,
jupyter终究是3个web应用, 存款和储蓄文件有不安宁的地方.
建议依旧利用pycharm那类的软件编写制定代码. 倘诺是用于写博客,
sublime能够安装插件copy as html jupyter对于copy的优化不够.
尤其是离线图片保存起来是不能展现的.
近来推出的一个工具,帮Jupyter Notebook把那些短板补齐了。
诸如,
你要向外人解释你的先后, 你恐怕要新建2个word, 把代码复制进去,
对每块代码举行讲解. 那样会有多少个难题, 壹) 代码格式不佳看; 二)
代码的配色丢失; 三) 代码与文字表明部分界别不分明. 使用Jupyter Notebook,
能够让代码保持其在编辑器里面包车型大巴格式, 看起来很正规. 而且, 复制进去的代码是足以运作的. 敲击完代码之后,
按Shift+Enter, 或许地点的Run Cell键变能够获得代码运转结果. 那里,
写Notebook时候, 都是以cell为基本单位的, cell有几连串型: 如code, markdown, heading等. 倘若设置为code类型,
里面包车型大巴内容正是能够运转的;
heading类型的cell能够支持大家设置标题(一级,二级,三级等标题),
markdown类型的cell能够使大家用markdown的语法来编排文本.
jupyter详细教程
以此工具叫Jupytext,顾名思义,能够把Jupyter
Notebook的内容转化成纯文本,用你最顺手的IDE展开。
Python·Jupyter Notebook种种应用方法记录·持续立异
图二 Jupyter Noteboook代码示例
标签(空格分隔): Python
于是乎,编辑同盟版本调节等1系列难点,一蹴而就。
文书档案写好之后,
保存成为1般的.ipynb的格式,
可是也得以保留成此外的格式, 如: Python(.py), 马克down(.md), HTML(.html),
reST(.rst), PDF via Latex(.pdf), Presentation(.html).
Jupytext今后协理的言语还不可能覆盖Jupyter
Notebook的满贯,但化解了最盛行的两种。它扶助Jupyter
Notebook和下部那些格式之间的相互调换:
参考文献:
- PythonJupyter
Notebook各个应用办法记录不断立异 -
一
Jupyter
NoteBook的安装- 1 新版本Anaconda自带Jupyter
- 二 老版本Anacodna需本身安装Jupyter
-
二更换Jupyter
notebook的干活空间- 1Jupyter的做事空间在哪儿钦定
- 二怎么着找到该配置文件
-
三Jupyter的各样连忙键
-
4Jupyter
Notebook怎么样导入代码- 1 将当地的py文件load到jupyter的3个cell中
- 2 从网络load代码到jupyter
-
五Jupyter运行python文件
-
6Jupyter局部别样琐碎用法
- 一 jupyter的cell能够当做unix
command使用 - 2 Magic
functions - 3 获取current working
directory - 4 使用Matplotlib绘图
- 一 jupyter的cell能够当做unix
-
七Jupyter中的Markdown
- 壹 在jupyter中设置link须求设置两局地
- 二 为Jupyter
Notebook增添目录效率
Julia脚本(.jl)、Python脚本(.py)、R脚本(.R)、Markdown文件(.md)、R
Markdown文件(.Rmd)。
[1] Jupyter
Notebook连忙入门:
Jupytext我Marc
Wouts在一篇博客里显示了什么样借助这么些工具在IDE或许编辑器里来编辑Jupyter
Notebook、进行版本调控。
Jupyter notebook )前身为IPython Notebook,学习时,能够找两者的学科
地点就是Jupytext使用进度的3个例子:把叁个Jupyter
Notebook存款和储蓄为.ipynb和.py二种文件格式、用PyCharm张开.py脚本来修改代码、保存之后刷新浏览器,就能在Jupyter
Notebook里看到新结果了。
- Jupyter Project
Documentation - Jupyter Notebook
Documentation - Jupyter/IPython
Notebook Quick Start
Guide - Old IPython
Notebook Homepage
想要在一大堆代码和笔记里搜索内容、编辑、施行cell、debug……用IDE比用Jupyter
Notebook要便宜得多。
一、
Jupyter NoteBook的安装
上海图书馆则是对文本施行版本检查,然后将有意义的差距合并的经过。
1.1 新版本Anaconda自带Jupyter
看起来不错,怎么设置呢?
- 时下,最新版本的Anaconda是自带Jupyter
NoteBook的,不要求再独自安装
其一工具援助pypi.安装,代码是这么的:
一.贰 老版本Anacodna需本身安装Jupyter
upytext frompip
Jupyter Notebook安装的官网
pip install jupytext –upgrade
- 安装Jupyter
Notebook的先决条件:已经安装了python(python
2.7 或者是python3.3) -
实际的装置情势:
- 合法建议使用Anaconda安装Jupyter
- 安装完结Anaconda后,假诺该Anaconda并不自带Jupyter
Noterbook,那么,展开cmd,输入:conda install
jupyter
-
那样设置完的jupyter不享有New a terminal的效应
透过各个查询才清楚,原来是因为windows不抱有terminal须求的TTY,所以,windows下的jupyter是不协助Terminal格局的,而且长时间内也从不扩充那种支撑的安排2、 更换Jupyter notebook的劳作空间
二.一 Jupyter的职业空间在哪儿钦定?
在其配备文件ipython_notebook_config.py中,有如下一句
# The directory to use for notebooks
and kernels.
# Append this to .jupyter/jupyter_notebook_config.py
c.NotebookApp.contents_manager_class=”jupytext.TextFileContentsManager”
\#
c.NotebookApp.notebook\_dir = u''
- 1
- 2
- 3
- 1
- 2
- 3
该句就是用来指定其工作空间的,例如,默认的工作空间是:用户名文件夹,例如,现在想要将工作空间变为D:\\Jupyter,那么,需要做如下更改(要记得删掉注释\#)
\# The directory to use for
notebooks and kernels.
c.NotebookApp.notebook\_dir = u'D:\\Jupyter'
**这句话很容易抄错, ''前面是u ,还要去掉\#号, 而且你要在本地建立一个文件夹, 如果文件夹不存在也会出错. **
- 1
- 2
- 3
- 1
- 2
- 3
注意:路径最后一级后面不要加符号"\\"
2.2 如何找到该配置文件?
参考目录C:\\Users\\Administrator\\.jupyter
- 在cmd中输入jupyter notebook
--generate-config
- 如果该配置文件已经存在,那么,会出现如下信息,从中可以见到配置文件存在的位置,注意,此时,输入N,不要overwrite

- 如果该配置文件不存在,那么,将会初始化产生一个配置文件
在cmd中输入:ipython profile
create
可以找到关于jupyter的配置文件的位置
三、Jupyter的各种快捷键
- 执行当前cell,并自动跳到下一个cell:Shift
Enter
- 执行当前cell,执行后不自动调转到下一个cell:Ctrl-Enter
- 是当前的cell进入编辑模式:Enter
- 退出当前cell的编辑模式:Esc
- 删除当前的cell:双D
- 为当前的cell加入line number:单L
- 将当前的cell转化为具有一级标题的maskdown:单1
- 将当前的cell转化为具有二级标题的maskdown:单2
- 将当前的cell转化为具有三级标题的maskdown:单3
- 为一行或者多行添加/取消注释:Crtl
/
- 撤销对某个cell的删除:z
- 浏览器的各个Tab之间切换:Crtl
PgUp和Crtl
PgDn
- 快速跳转到首个cell:Crtl
Home
- 快速跳转到最后一个cell:Crtl
End
四、Jupyter Notebook如何导入代码
即导入代码到jupyter notebook的cell中
4.1 将本地的.py文件load到jupyter的一个cell中
**问题背景**:有一个test.py文件,需要将其载入到jupyter的一个cell中
test.py内容如下:
import
caffe
SolverName = "/root/workspace"
sovler =
caffe.AdamSolver(SolverName)
- 1
- 2
- 3
- 1
- 2
- 3
**方法步骤**:
(1)在需要导入该段代码的cell中输入
%load test.py
\#test.py是当前路径下的一个python文件
- 1
- 1

(2)运行该cell
利用快捷键"Shift+Enter",可以看到如下结果:

(3)可以看到,运行后,%load
test.py被自动加入了注释符号\#,test.py中的所有代码都被load到了当前的cell中
4.2 从网络load代码到jupyter
- 在cell中输入%load
http://.....,然后运行该cell,就会将load后面所对应地址的代码load到当前的cell中;
- 下面给出一个例子,导入[matplotlib中的一个小例子](http://matplotlib.org/)[color example
code
](http://matplotlib.org/examples/color/color_cycle_demo.html)
-
首先,在想要导入该段代码的cell中输入
%load
test.py \#test.py是当前路径下的一个python文件
-
1
-
1
- 然后,Shift+Enter运行,可以看到如下结果:

可以看到,运行后,%load
test.py被自动加入了注释符号\#,test.py中的所有代码都被load到了当前的cell中
-
五、Jupyter运行python文件
- 利用jupyter的cell是可以运行python文件的,即在cell中运行如下代码:
%run file.py
- 1
- 1
file.py为要运行的python程序,结果会显示在该cell中


六、Jupyter一些其他琐碎用法
6.1 jupyter的cell可以作为unix command使用
具体方法为:在unitx command前面加入一个感叹号"!"
例子:
查看python版本:!python
--version
运行python文件:!python
myfile.py
6.2
Magic functions
还没有太明白,具体细节见[](http://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb)The
cell magics in IPython
6.3 获取current working directory
即当前运行的代码所在的路径
具体方法:current\_path =
%pwd
这样得到的current\_path就是当前工作路径的字符转
6.4 使用Matplotlib绘图
在Jupyter Notebook中,如果使用Matplotlib绘图,有时是弹不出图像框的,此时,可以在开头加入
%matplotlib
inline
- 1
- 1
七、Jupyter中的Markdown
[参考1](http://sebastianraschka.com/Articles/2014_ipython_internal_links.html)
[Markdown
](http://blog.leanote.com/post/freewalk/Markdown-%E8%AF%AD%E6%B3%95%E6%89%8B%E5%86%8C)语法手册
(完整整理版)参考
7.1 在jupyter中设置link,需要设置两部分:
- 要跳到的位置(the destination)
需要在要跳转到的位置添加下面语句:
<a id='the\_destination'></a>
- 1
- 1
这里的id取值任意赋值,下面在添加链接时要用
- 需要添加链接的文字(an internal hyperlink to the
destination),即点击该处可以跳转到the
destination,在需要添加链接的文字后面加入:
\[需要添加连接的文字\](\#the\_destination)
- 1
- 1
- 下面是一个例子:
源码:

效果图:

7.2 为Jupyter Notebook添加目录功能
- 原始的Jupyter是不支持markdown添加目录功能的
- 实际上,可以利用[Jupyter notebook
extensions去使得这种功能实现
](https://github.com/ipython-contrib/jupyter_contrib_nbextensions)
- -
具体方法:
- 利用Anaconda安装Jupyter Notebook
extensions
conda
install -c conda-forge
jupyter\_contrib\_nbextensions

- 打开Jupyter
Notebook,在它的(新增的)Nbextensions标签下勾选"Table of Contents(2)"

- 打开一个.jpynb文件,发现,目录功能可用了!


参考文献
\[1\] [](https://zhuanlan.zhihu.com/p/24029578?refer=learnMLb/jupyter_contrib_nbextensions)为Jupyter Notebook添加目录

顶
14
踩
0
[ ](javascript:void(0);)
[ ](javascript:void(0);)
- 上一篇[theano安装(一)windows配置安装theano环境(非GPU版)、keras
](http://blog.csdn.net/tina_ttl/article/details/51404165)
- -
下一篇[Docker学习系列(二):Ubuntu14.04下安装Docker-2016.06.26更新版
](http://blog.csdn.net/tina_ttl/article/details/51417193)
相关文章推荐
- -
• [Linux\_Swap持续增长的问题(tcpdump引入,与使用方法)](http://weimou66.iteye.com/blog/1479235)
- • [\[DL\]python使用相关工具说明](http://blog.csdn.net/zyh821351004/article/details/71336121)
- • [CSDNBlog使用方法(非官方,持续更新)(已更新二次)](http://soft-app.iteye.com/blog/911955)
- • [Jupyter notebook 使用
\[持续更新\]](http://blog.csdn.net/dachylong/article/details/55517632)
- • [《财富》专访杰夫·维纳:LinkedIn上市一年后如何自保并持续扩张](http://xwk.iteye.com/blog/2140699)
- • [如何高效的学习 TensorFlow
代码?](http://blog.csdn.net/forfuture3513/article/details/53204796)
- • [亚伦·赖金的节约时间的18种方法](http://hududanyzd.iteye.com/blog/1346000)
- • [在PyCharm环境中使用Jupyter
Notebook的两种方法](http://blog.csdn.net/xiemanR/article/details/71837385)
- • [gevent
任务的持续追加和执行(续·真)](http://iyuan.iteye.com/blog/897539)
- • [【电子基础】电子基础知识·持续更新](http://blog.csdn.net/hackdevil/article/details/9190467)
猜你在找
Jupyter
Notebook的27个秘诀,技巧和快捷键
文摘供稿

[原文链接](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/)
翻译:姜范波
校对:毛丽 &&
寒小阳
Jupyter
Notebook
Jupyther
notebook ,也就是一般说的
Ipython notebook,是一个可以把代码、图像、注释、公式和作图集于一处,从而实现可读性分析的一种灵活的工具。
Jupyter延伸性很好,支持多种编程语言,可以很轻松地安装在个人电脑或者任何服务器上——只要有ssh或者http接入就可以啦。最棒的一点是,它完全免费哦。

Jupyter 界面
默认情况下,Jupyter
Notebook 使用Python内核,这就是为什么它原名
IPython Notebook。Jupyter
notebook是Jupyter项目的产物——Jupyter这个名字是它要服务的三种语言的缩写:Julia,PYThon和R,这个名字与"木星(jupiter)"谐音。本文将介绍27个轻松使用Jupyter的小窍门和技巧。
1、快捷键
高手们都知道,快捷键可以节省很多时间。Jupyter在顶部菜单提供了一个快捷键列表:Help >
Keyboard Shortcuts 。每次更新Jupyter的时候,一定要看看这个列表,因为不断地有新的快捷键加进来。另外一个方法是使用Cmd +
Shift + P ( Linux 和
Windows下 Ctrl +
Shift + P亦可)调出命令面板。这个对话框可以让你通过名称来运行任何命令——当你不知道某个操作的快捷键,或者那个操作没有快捷键的时候尤其有用。这个功能与苹果电脑上的Spotlight搜索很像,一旦开始使用,你会欲罢不能。

几个我的最爱:
- Esc +
F 在代码中查找、替换,忽略输出。
- Esc +
O 在cell和输出结果间切换。
- 选择多个cell:
- Shift +
J 或 Shift +
Down 选择下一个cell。
- Shift +
K 或 Shift + Up
选择上一个cell。
- 一旦选定cell,可以批量删除/拷贝/剪切/粘贴/运行。当你需要移动notebook的一部分时这个很有用。
- Shift +
M 合并cell.

2、变量的完美显示
有一点已经众所周知。把变量名称或没有定义输出结果的语句放在cell的最后一行,无需print语句,Jupyter也会显示变量值。当使用Pandas
DataFrames时这一点尤其有用,因为输出结果为整齐的表格。
鲜为人知的是,你可以通过修改内核选项ast\_note\_interactivity,使得Jupyter对独占一行的所有变量或者语句都自动显示,这样你就可以马上看到多个语句的运行结果了。
# And restart your notebook server
-
In [1]: from IPython.core.interactiveshell
import InteractiveShell -
InteractiveShell.ast_node_interactivity = “all”
-
In [2]: from pydataset import data
-
quakes
= data(‘quakes’) -
quakes.head()
jupyter notebook
- quakes.tail()
都被这么些新工具补齐了,初学者需求IPython。在Jupyter
Notebook的元数据里输入jupytext_formats,就能激活台式机和文件文件的配对,达成在IDE里编辑脚本,Notebook里也随后更新的功效。
- Out[2]:
假定想在编辑文本文件的时候还开着Jupyter,能够在三个单元格里运维%autosave
0,关掉Jupyter的自发性保存效能。
-
lat
long depth mag
stations -
1 -20.42 181.62 562 4.8 41
-
2 -20.62 181.03 650 4.2 15
-
3 -26.00 184.10 42 5.4 43
-
4 -17.97 181.66 626 4.1 19
-
5 -20.42 181.96 649 4.0 11
-
Out[2]:
-
lat
long depth mag
stations -
996 -25.93 179.54 470 4.4 22
-
997 -12.28 167.06 248 4.7 35
-
998 -20.13 184.20 244 4.5 34
-
999 -17.40 187.80 40 4.5 14
-
1000 -21.59 170.56 165 6.0 119
最后,附上Jupytext的传送门:
若果你想在种种气象下(Notebook和Console)Jupyter都一样处理,用下边包车型大巴几行轻便的一声令下创造文件~/.ipython/profile_default/ipython_config.py就可以达成:
1. c
get\_config()
-
#
Run all nodes interactively -
c.InteractiveShell.ast_node_interactivity = “all”
3、轻便链接到文书档案
在Help 菜单下,你能够找到常见库的在线文档链接,包蕴Numpy,Pandas,Scipy和Matplotlib等。
除此以外,在库、方法或变量的后面打上?,就能够张开相关语法的相助文书档案。
- In [3]: ?str.replace()
Docstring:
S.replace(old,
new[, count]) -> str
Return
a copy of S with all occurrences of substring
old
replaced by new. If the optional argument count is
given,
only the first count occurrences are replaced.
Type:
method_descriptor
4、 在notebook里作图
在notebook里作图,有四个挑选:
– matplotlib (事实标准),可通过%matplotlib
inline 激活,详尽链接
- %matplotlib notebook 提供交互性操作,但或者会有点慢,因为响应是在劳务器端达成的。
– mpld3 提供matplotlib代码的代替性显示(通过d三),纵然不完整,但很好。
– bokeh 生成可互相图像的越来越好选拔。
– plot.ly 能够改动相当好的图,可惜是付费服务。
5、 Jupyter
Magic命令
上文提到的%matplotlib
inline 是Jupyter
Magic命令之一。
引进阅读Jupyter
magic命令的连锁文书档案,它一定会对您很有援救。上边是小编最爱的多少个:
陆、
Jupyter Magic-%env:设置环境变量
无需重启jupyter服务器进度,也能够管理notebook的环境变量。有的库(比如theano)使用环境变量来决定其表现,%env是最有利于的渠道。
In
[55]: # Running %env without any arguments
#
lists all environment variables
#
The line below sets the environment
#
variable OMP_NUM_THREADS
%env
OMP_NUM_THREADS=4
env:
OMP_NUM_THREADS=4
7、Jupyter Magic – %run:
运行python代码
%run 能够运营.py格式的python代码——那是明显的。不那么为人精晓的真相是它也得以运作其余的jupyter notebook文件,那一点很有用。
注意:使用%run 与导入2个python模块是例外的。
In
[56]: # this will execute and show the output from
#
all code cells of the specified notebook
%run
./two-histograms.ipynb
8、Jupyter Magic
-%load:从表面脚本中插入代码
该操功效外部脚本替换当前cell。能够使用你的Computer中的四个文件作为来自,也得以应用ULX570L。
In
[ ]: # Before Running
%load
./hello_world.py
In
[61]: # After Running
#
%load ./hello_world.py
if
__name__ == “__main__”:
print(“Hello
World!”)
Hello
World!
玖、Jupyter Magic – %store:
在notebook文件之间传递变量
%store 命令可以在三个notebook文件之间传递变量。
In
[62]: data = ‘this is the string I want to pass to different notebook’
%store
data
del
data # This has deleted the variable
Stored
‘data’ (str)
至今,在三个新的notebook文书档案里……
In
[1]: %store -r data
print(data)
this
is the string I want to pass to different notebook
十、Jupyter Magic – %who:
列出全数的全局变量
不加任何参数, %who 命令可以列出全体的全局变量。加上参数 str 将只列出字符串型的全局变量。
In
[1]: one = “for the money”
two
= “for the show”
three
= “to get ready now go cat go”
%who
str
one
three two
11、Jupyter Magic –
计时
有三种用于计时的jupyter magic命令: %%time 和 %timeit.当你有局部很耗费时间的代码,想要查清楚难题出在哪时,那多个指令万分给力。
周全回味下自家的讲述哦。
%%time 会告诉你cell内代码的单次运转时刻新闻。
In
[4]: %%time
import
time
for
_ in range(1000):
time.sleep(0.01)#
sleep for 0.01 seconds
CPU
times: user 21.5 ms, sys: 14.8 ms, total: 36.3 ms
Wall
time: 11.6 s
%%timeit 使用了Python的
timeit 模块,该模块运维某语句100,000次(暗中认可值),然后提供最快的二回的平均值作为结果。
In
[3]: import numpy
%timeit
numpy.random.normal(size=100)
The
slowest run took 7.29 times longer than the fastest. This could mean
that an intermediate result is being cached.
100000
loops, best of 3: 5.5 µs per loop
1二、Jupyter Magic – %%writefile
and %pycat:导出cell内容/显示外部脚本的始末
使用%%writefile magic能够保留cell的始末到表面文件。 而%pycat作用相反,把外部文件语法高亮呈现(以弹出窗格局)。
In
[7]: %%writefile pythoncode.py
import
numpy
def
append_if_not_exists(arr, x):
if
x not in arr:
arr.append(x)
金沙网址 ,def
some_useless_slow_function():
arr
= list()
for
i in range(10000):
x
= numpy.random.randint(0, 10000)
append_if_not_exists(arr,
x)
Writing
pythoncode.py
In
[8]: %pycat pythoncode.py
import
numpy
def
append_if_not_exists(arr, x):
if
x not in arr:
arr.append(x)
def
some_useless_slow_function():
arr
= list()
for
i in range(10000):
x
= numpy.random.randint(0, 10000)
append_if_not_exists(arr,
x)
一三、Jupyter Magic – %prun:
告诉你程序中种种函数消耗的年月
使用%prun+函数评释会给你一个按顺序排列的报表,显示各类内部函数的耗费时间意况,每一遍调用函数的耗时景况,以及一同耗费时间。
In
[47]: %prun some_useless_slow_function()
26324
function calls in 0.556 seconds
Ordered
by: internal time
ncalls
tottime percall cumtime percall filename:lineno(function)
10000
0.527 0.000 0.528 0.000
<ipython-input-46-b52343f1a2d5>:2(append_if_not_exists)
10000
0.022 0.000 0.022 0.000 {method ‘randint’ of ‘mtrand.RandomState’
objects}
1
0.006 0.006 0.556 0.556
<ipython-input-46-b52343f1a2d5>:6(some_useless_slow_function)
6320
0.001 0.000 0.001 0.000 {method ‘append’ of ‘list’ objects}
1
0.000 0.000 0.556 0.556 <string>:1(<module>)
1
0.000 0.000 0.556 0.556 {built-in method exec}
1
0.000 0.000 0.000 0.000 {method ‘disable’ of ‘_lsprof.Profiler’
objects}
1四、Jupyter Magic –用%pdb调节和测试程序
Jupyter 有和好的调剂界面The Python
Debugger (pdb),使得进入函数内部检查错误成为恐怕。
Pdb中可利用的指令见链接
In
[ ]: %pdb
def
pick_and_take():
picked
= numpy.random.randint(0, 1000)
raise
NotImplementedError()
pick_and_take()
Automatic
pdb calling has been turned ON
NotImplementedError
Traceback (most recent call last)
<ipython-input-24-0f6b26649b2e>
in <module>()
5
raise NotImplementedError()
6
—->
7 pick_and_take()
<ipython-input-24-0f6b26649b2e>
in pick_and_take()
3
def pick_and_take():
4
picked = numpy.random.randint(0, 1000)
—->
5 raise NotImplementedError()
6
7
pick_and_take()
NotImplementedError:
>
<ipython-input-24-0f6b26649b2e>(5)pick_and_take()
3
def pick_and_take():
4
picked = numpy.random.randint(0, 1000)
—->
5 raise NotImplementedError()
6
7
pick_and_take()
ipdb>
一5、末句函数不出口
偶尔不让末句的函数输出结果比较便宜,比如在作图的时候,此时,只需在该函数末尾加上2个子集团就能够。
In
[4]: %matplotlib inline
from
matplotlib import pyplot as plt
import
numpy
x
= numpy.linspace(0, 1, 1000)**1.5
In
[5]: # Here you get the output of the function
plt.hist(x)
Out[5]:
(array([
216., 126., 106., 95., 87., 81., 77., 73., 71., 68.]),
array([
- , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
<a
list of 10 Patch objects>)
In
[6]: # By adding a semicolon at the end, the output is suppressed.
plt.hist(x);
16、运行Shell命令
在notebook内部运转shell命令很简短,那样您就能够见见你的职业文件夹里有啥样数据集。
In
[7]: !ls *.csv
nba_2016.csv
titanic.csv
pixar_movies.csv
whitehouse_employees.csv
17、用LaTex 写公式
当您在一个马克down单元格里写LaTex时,它将用MathJax显示公式:如
$$ P(A \mid B) = \frac{P(B \mid A) , P(A)}{P(B)} $$
会变成
1八、在notebook内用差别的基本运转代码
壹经你想要,其实能够把差别基础的代码结合到多少个notebook里运维。
只需在种种单元格的原初,用Jupyter magics调用kernal的称谓:
- %%bash
- %%HTML
-
%%python2
-
%%python3
-
%%ruby
- %%perl
- In [6]: %%bash
- for i in {1..5}
-
do
-
echo “i is $i”
- done
i
is 1
i
is 2
i
is 3
i
is 4
i
is 5
1玖、给Jupyter安装其余的基业
Jupyter的上佳天性之1是能够运作分裂语言的内核。上边以运维Rubicon内核为例表明:
一言以蔽之的主意:通过Anaconda安装途达内核
conda
install -c r r-essentials
有个别麻烦的措施:手动安装纳瓦拉内核
假使你不是用Anaconda,进度会有点复杂,首先,你要求从CRAN安装ENVISION。
尔后,运营ENVISION调整台,运转上边包车型客车语句:
install.packages(c(‘repr’,
‘IRdisplay’, ‘crayon’, ‘pbdZMQ’, ‘devtools’))
devtools::install_github(‘IRkernel/IRkernel’)
IRkernel::installspec()
# to register the kernel in the current R installation
20、在同2个notebook里运维奥迪Q5和Python
要如此做,最棒的不二等秘书籍事安装rpy2(需求贰个方可干活的途锐),用pip操作很简短:
pip install rpy2
接下来,就可以同时接纳三种语言了,甚至变量也能够在贰者之间公用:
In
[1]: %load_ext rpy2.ipython
In
[2]: %R require(ggplot2)
Out[2]:
array([1], dtype=int32)
In
[3]: import pandas as pd
df
= pd.DataFrame({
‘Letter’:
[‘a’, ‘a’, ‘a’, ‘b’, ‘b’, ‘b’, ‘c’, ‘c’, ‘c’],
‘X’:
[4, 3, 5, 2, 1, 7, 7, 5, 9],
‘Y’:
[0, 4, 3, 6, 7, 10, 11, 9, 13],
‘Z’:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
})
In
[4]: %%R -i df
ggplot(data
= df) + geom_point(aes(x = X, y= Y, color = Letter, size = Z))
贰壹、用其余语言写函数
突发性numpy的过程有点慢,作者想写一些越来越快的代码。
标准上,你能够在动态Curry编写翻译函数,用python来封装…
可是1旦这几个无聊的历程不用本身干,岂不越来越好?
您能够在cython或fortran里写函数,然后在python代码里间接调用。
率先,你要先安装:
!pip
install cython fortran-magic
In
[ ]: %load_ext Cython
In
[ ]: %%cython
def
myltiply_by_2(float x):
return
2.0 * x
In
[ ]: myltiply_by_2(23.)
本人个人相比较喜欢用Fortran,它在写数值总括函数时尤其便于。越多的底细在这里。
In
[ ]: %load_ext fortranmagic
In
[ ]: %%fortran
subroutine
compute_fortran(x, y, z)
real,
intent(in) :: x(:), y(:)
real,
intent(out) :: z(size(x, 1))
z
= sin(x + y)
end
subroutine compute_fortran
In
[ ]: compute_fortran([1, 2, 3], [4, 5, 6])
还有一对其余跳转系统能够加速python 代码。越来越多的例证见链接:
2二、扶助多指针
Jupyter支持两个指针同步编辑,类似Sublime Text编辑器。按下Alt键并拖拽鼠标就可以兑现。
二三、Jupyter外接拓展
Jupyter-contrib
extensions是一对授予Jupyter越来越多更能的拉开程序,包罗jupyter spell-checker和code-formatter之类.
下边包车型大巴一声令下安装那个延伸程序,同时也设置叁个菜单情势的配置器,能够从Jupyter的主显示器浏览和激活延伸程序。
!pip
install
!pip
install jupyter_nbextensions_configurator
!jupyter
contrib nbextension install –user
!jupyter
nbextensions_configurator enable –user
二四、从Jupyter notebook成立示范稿
Damian Avila的翼虎ISE允许你从已有个别notebook成立八个powerpoint形式的演示稿。
您能够用conda来安装CRUISERISE:
conda
install -c damianavila82 rise
或者用pip安装:
pip
install RISE
然后运营下边包车型客车代码来设置和激活延伸程序:
jupyter-nbextension
install rise –py –sys-prefix
jupyter-nbextension
enable rise –py –sys-prefix
二伍、Jupyter输出系统
Notebook自己以HTML的样式体现,单元格输出也能够是HTML方式的,所以你能够出口任胡秋生西:录像/音频/图像。
以此事例是浏览小编全数的图纸,并出示前5张图的缩略图。
In
[12]: import os
from
IPython.display import display, Image
names
= [f for f in os.listdir(‘..ml_demonstrations/’) if
f.endswith(‘.png’)]
for
name in names[:5]:
display(Image(‘..ml_demonstrations/’
- name, width=100))
小编们也能够用bash命令创设三个平等的列表,因为magics和bash运转函数后赶回的是python 变量:
In
[10]: names = !ls ..ml_demonstrations/*.png
names[:5]
Out[10]:
[‘..ml_demonstrations/colah_embeddings.png’,
‘..ml_demonstrations/convnetjs.png’,
‘..ml_demonstrations/decision_tree.png’,
‘..ml_demonstrations/decision_tree_in_course.png’,
‘..ml_demonstrations/dream_mnist.png’]
二陆、大数据解析
数不清方案得以化解查询/处理大额的标题:
-
ipyparallel(在此以前叫 ipython cluster) 是贰个在python中展开简易的map-reduce运算的优秀选取。大家在rep中接纳它来并行练习诸多机器学习模型。
-
pyspark
- spark-sql
magic %%sql
27、分享notebook
享用notebook最方便的艺术是运用notebook文件(.ipynb),可是对那多少个不选拔notebook的人,你还有这么些选取:
- 通过File > Download as > HTML
菜单转变来html文件。
- 用gists可能github分享你的notebook文件。那八个都得以展现notebook,示例见链接
-
如若您把温馨的notebook文件上传到github的货仓,能够应用很方便的Mybinder服务,允许另一人实行半个小时的Jupyter交互连接受你的库房。
-
用jupyterhub建立你协调的系统,那样您在集体微型课堂或许事业坊,无暇顾及学生们的机器时就10分便利了。
-
将您的notebook存款和储蓄在像dropbox那样的网址上,然后把链接放在nbviewer,nbviewer能够显示任意来源的notebook。
-
用菜单File > Download as >
PDF 保存notebook为PDF文件。借使你挑选本办法,小编强烈提出你读1读Julius Schulz的文章 -
用Pelican从你的notebook创建1篇博客。
— 完—回到和讯,查看越来越多
主要编辑: