美文网首页计算机@linux_python_R 技术帖
轻松优化Jupyter Notebook:技巧、诀窍、魔法

轻松优化Jupyter Notebook:技巧、诀窍、魔法

作者: CurryCoder | 来源:发表于2019-06-28 10:29 被阅读42次

    0.更换主题

    pip install jupyterthemes
    
    # 使用暗黑主题
    jt -t chesterish
    
    # 恢复默认主题
    jt -r
    

    1.常用技巧

    ctrl + shift + p  # 查看所有的快捷键按钮 
    
    # 如果在开头加上感叹号,则可以运行bash命令,例如: !pip install numpy
    
    # 在某个函数的末尾加上分号来随时限制函数在最后一行代码上的输出
    
    ctr + /   # 用来注释或者取消代码
    

    2.MarkDown模式

    在markdown模式下支持latex 例如:p(A \mid B) = \frac{p(B \mid A)p(A)}{p(B)}

    3.输出打印

    # 打印出所有输出
    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "all"
    
    # 打印最后一行输出
    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "last_expr"
    
    

    4.安装扩展插件

    • 安装Nbextensions
      • pip安装
            pip install jupyter_contrib_nbextensions
            jupyter contrib nbextension install --user
        
      • Anaconda安装
            conda install -c conda-forge jupyter_contrib_nbextensions
            conda install -c conda-forge jupyter_nbextensions_configurator
            jupyter contrib nbextension install --user
        

    5.魔法函数

    • line magic在一条线上使用,以%开头
    • cell magic # 在整个cell上使用,以%%开头
    %lsmagic   # 查看所有的魔法函数
    %env    # 查看环境变量
    

    6.文件的导入与导出

    # 在cell中插入外部的py文件 
    %load basic_import.py
    
    # 将cell中的代码导出到一个py文件中
    %%writefile thiscode.py
    

    7.运行与查看导入的文件

    # 运行py文件中的内容
    %run basic_import.py
    
    # 不确定脚本文件中的内容,可以随时显示它
    %pycat basic_import.py
    

    8.设置自动保存

    %autosave 60  # 每60秒自动保存
    

    9.显示图像

    %matplotlib inline
    

    10.定时器

    • %timeit和%%time放在需要指定的语句前,例如:%%time print("hello python!")
    %%time       # 计算给出cell中的代码运行一次所花费的时间
    %timeit      # 多次运行指定的代码计算平均值,使用的是python中的timeit模块
    

    11.运行其他语言的代码

    • 在不同放入kernel中运行代码,在kernel的开头加上下面对应语言的语句才可以使用!
    %%bash
    %%HTML
    %%python
    %%python2
    %%python3
    %%ruby
    %%perl
    %%capture
    %%javascript
    %%js
    %%latex
    %%markdown
    %%pypy
    

    12.查看变量

    # 查找全局范围内的所有变量
    %who 
    %who str  # 只查看str类型的变量
    # 查看执行某个函数花费的实际
    %prun 语句名
    # 使用pdb进行调试
    必须在每个cell的开头,加上%pdb
    
    

    13.提供高分辨率的图

    %config InlineBackend.figure_format = 'retina'
    

    14.选择执行某些cell

    %%script false     # 在cell的开头加上此句
    

    15.当需要一直运行某段代码时,通过下面的方法提醒我们的代码何时跑完

    # 预先安装sox:
    brew install sox  (mac上)
    # Linux/Mac系统上:
    import os
    duration = 1 // second
    freq=440
    os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration,freq))
    
    # Windows系统上:
    import winsound
    duration = 1000
    freq = 440
    winsound.Beep(freq.duration)
    

    16.参考博客

    相关文章

      网友评论

        本文标题:轻松优化Jupyter Notebook:技巧、诀窍、魔法

        本文链接:https://www.haomeiwen.com/subject/rwxscctx.html