鹤啸九天 自律更自由,平凡不平庸 Less is More

Jupyter notebook 学习笔记

2016-06-26
阅读量

Notes(温馨提示):

  1. ★ 首次阅读建议浏览:导航指南
  2. 右上角工具条搜索文章,右下角二维码关注微信公众号(鹤啸九天),底栏分享、赞赏、评论
  3. ★ 转载请注明文章来源,知识点积累起来不容易,水滴石穿,绳锯木断,谢谢理解
  4. ★ 如有疑问,邮件讨论,欢迎贡献优质资料


jupyter notebook

  • Jupyther notebook ,也就是一般说的 Ipython notebook,是一个可以把代码、图像、注释、公式和作图集于一处,从而实现可读性分析的一种灵活的工具。
  • 默认情况下,Jupyter Notebook 使用Python内核,这就是为什么它原名 IPython Notebook。Jupyter notebook是Jupyter项目的产物——Jupyter这个名字是它要服务的三种语言的缩写:Julia,Python和R,这个名字与“木星(jupiter)”谐音。

jupyter 教程

Jupyter资源与工具库大全

  • Notebook环境 13 个项目
  • 交互式小部件和可视化 49 个项目
  • Jupyter拓展 23 个项目
  • Jupyter-magic拓展 10 个项目
  • Jupyter内核 36 个项目
  • Jupyter-Notebook分享与格式转换 23 个项目
  • Jupyter-Notebook工具 24 个项目
  • JupyterLab渲染器 7 个项目
  • JupyterLab主题 8 个项目
  • JupyterLab扩展 50 个项目
  • JupyterHub认证 15 个项目
  • JupyterHub容器等 8 个项目
  • Jupyter组件 3 个项目
  • Others 4 个项目

安装

  • 安装:
pip install jupyter
  • 速度慢?设置清华源:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

扩展功能

加强版+自定义主题

安装以下插件可以启动加强版功能

  • 功能:
    • 目录:Table of Content
    • 自动保存:autosave time
    • 代码折叠:codfolding、codefolding in editor
    • 颜色高亮:选中单词高亮,highlighter、 highlight selected word
    • 启动jupyter服务后,在web主页,点击”Nbextensions”,勾选对应功能
  • 主题定制
# 安装扩展插件,含目录插件
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
# 跟上面什么区别?
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
#重启jupyter

# 安装jupyter主题包
pip install jupyterthemes
#更新主题
pip install --upgrade jupyterthemes 
# 启用主题
jt -t grade3 -f fira -fs 13 -cellw 90% -ofs 11 -dfs 11 -T 
# 启动jupyter服务

更换 conda kernel

jupyter notebook 启动后,有默认的 kernel(Python版本)

问题:

  • 使用 miniconda 创建虚拟环境后,jupyter 无法使用

【2024-3-8】解决:关联 conda 虚拟环境

# 准备虚拟环境
conda create -n py38 python=3.8 pytorch
source ~/miniconda3/etc/profile.d/conda.sh # 如果提示要先 conda init,而实际上不起作用时,执行此句
conda activate py38 # 激活环境, 非必须
# 安装 ipykernel
pip install ipykernel
# 关联 conda 环境: py38
python -m ipykernel install --user --name py38 --display-name "Python (py38)"
# jupyter notebook 页面设置:左上角 Kernel → Change Kernel, 或 右上角 → 虫子区域附近的Python版本显示 → 点击等待1min,就能看到新建的 conda 环境名

服务启动

常规启动

问题

  • 【2024-3-6】设置本机ip,启动jupyter报错

解决:

  • 临时解法:
    • 将ip值设置为 0.0.0.0
    • 启动服务后,复制生成的链接, 手工修改ip为真实ip
      • 整串贴到浏览器
      • 或贴域名部分,然后填入token
  • 永久解法: 重新设置 jupyter远程访问,【2024-3-6】实践失败,远程token配置无解
wqw@singapore:~$ jupyter notebook --ip=0.0.0.0 --port=8888
# 报错: OSError: [Errno 99] Cannot assign requested address
# http://127.0.0.1:8888/?token=bae33029f5f21e2c01e51c499287874828e5eda5eec483e2
# http://8.219.219.248:8888/?token=bae33029f5f21e2c01e51c499287874828e5eda5eec483e2
# http://8.219.219.248:8888, 填入token

远程访问

详细步骤如下:

  • 查看服务端ip:
ifconfig \| grep "inet " \| grep -v 127.0.0.1 # 如ip=10.97.182.142
  • 生成配置文件:
# 服务端
jupyter notebook --generate-config

打开ipython,生成密码:

  • 服务端终端输入:ipython
  • 继续输入:
from notebook.auth import passwd;passwd() # python2
from IPython.lib import passwd;passwd() # python3
# python>3.8上述方法已失效:AttributeError: module 'IPython.lib' has no attribute 'passwd'
python -c "from notebook.auth import passwd; print(passwd())" # python 3.10
# 输入访问密码
# 复制生成的密文:'sha:ce.....',

【2023-10-23】python>3.8上述方法已失效:AttributeError: module ‘IPython.lib’ has no attribute ‘passwd’

  • 新版ipython (8.*)不支持以上操作, the module security is missing…
# ---- 仅适用于 ipython 7系列 ----
import IPython.lib.security as security
security.passwd()
# ---------------------------
from notebook.auth import passwd # 无效,依然无法识别
hash=passwd('example')
hash=passwd('example', 'sha1')
# ------ 回退到7也不行 ------
pip install ipython==7.23.1

无解中

【2023-3-4】jupyternotebook

  • 修改配置文件
vim ~/.jupyter/jupyter_notebook_config.py
# 更新如下参数:
c.NotebookApp.ip='*' # 就是设置所有ip皆可访问
c.NotebookApp.password = u'sha:ce...' # 刚才复制的那个密文'
c.NotebookApp.open_browser = False # 禁止自动打开浏览器
c.NotebookApp.port =8888 # 随便指定一个端口
  • 启动服务端jupyter
# 执行:
jupyter notebook --ip=10.84.154.79 # ip可以省略
jupyter notebook --allow-root # 允许root账户
# 扔后台:
nohup jupyter notebook --ip=10.84.154.79 &
  • 客户端访问:http://10.97.182.142:8888/tree
    • 初次需要账户登录,输入设置过的访问密码
  • 注:请及时替换ip
jupyter notebook --no-browser --port 6000 --ip=192.168.1.103
  • [2018-1-4]如果依赖python虚拟环境(virtualenv),需要先激活再启动notebook
source ~/wqw/bin/activate
nohup jupyter notebook --ip=`ifconfig eth | awk '/inet/{print $2}'` &>log.txt &
nohup jupyter notebook --ip=10.37.139.225 &>log_notebook.txt & # 不指定ip也行

常见命令

魔法命令如下:

# %%file方法可以将脚本代码写入本地Py文件。
%%file hello.py
# 直接执行Py文件,通过%run方法来实现。
%run hello.py
# 监控代码运行时间
%timeit [x**2 for x in range(100)] 
# 调用系统命令
my_dir = 'new_dir'
!mkdir $my_dir
# 快速调试debug
def some_func():
    var = 'hello world'
    for i in range(5):
        print(i)
    i / 0
    return 'finished'

%debug
some_func()

特殊功能

魔法操作介绍

【2022-11-18】

  • 魔法操作介绍
  • 玩转Jupyter Notebook3
  • windows有8个默认指令:copy, echo, ldir, ls, mkdir, ren, rmdir
  • Linux下有16个默认指令: cat, clear, cp, ldir, less, ls, lk, ll, ls, lx, man, mkdir, mv, rm, rmdir
%lsmagic # 列出所有magics命令
%alias? # 输出某个魔法命令(如 alias)详细帮助文档
alias test echo "hello" # 设置别名
# ---- line 魔法指令 ------
%conda install package_names # conda 安装
%dhist # 输出历史访问目录
%history # 列出历史输入的指令
%magic # 输出所有魔法指令帮助文档
%matplotlib inline # 效果等价于plt.show()
%notebook # 导出当前notebook历史输入到文件
%notebook notebook.ipynb # 将所有历史输入导入notebook.ipynb文件中
%pip # 在cell中使用pip指令
%pwd # 输出当前路径
%pycat # 预览文件,类似linux中cat
%run # 执行脚本
%time # 执行时间
# ---- cell 魔法指令 ------
%%writefile # 将当前cell中内容写入文件中
%%latex # 写Latex公式
%%script # 写bash、perl、javascript、js 等命令, 不过经过测试,在jupyter notebook中不友好,在ipython中没什么问题。
%%script bash # bash环境
%%script python2 # py2

# 清楚变量
%reset # 魔法命令清除所有的变量、名称空间和引用
del variable_name # Python等效

IPython 有一个 %% script 魔法操作符, 可以在一个子进程中运行其它语言的解释器,包括: bash, ruby, perl, zsh, R, 等等

# ------ python ------
%%script python3
import sys
print('hello from Python: %s' % sys.version)
# ------ ruby ------
%%ruby
puts "Hello from Ruby #{RUBY_VERSION}" # Hello from Ruby 2.1.5
# ------ shell -----
%%bash
echo "hello from $BASH" # hello from /bin/bash

显示魔法命令

%lsmagic

shell

!后面跟上终端命令即可执行

  • Jupyter uses a temporary subshell. If you want to change to another directory permanently, you have to use the magic command %cd.
  • jupyter启用子shell,执行命令,不会作用到全局,如果需要更改目录,使用 %cd

单行代码

  • 值传递
directory = !pwd # 变量赋值
a = !ls

切换目录

  • %后面跟上命令
  • With the %automagic function, these can also be used without the preceding % character:
!pwd # 旧目录
%cd .. # 切换目录
!pwd # 新目录
#--------
%automagic # 开启自动识别,可以省略 %
cd ..

shell 代码块

%%!
ls -l
pwd

执行时间

# ---------
import numpy as np
%timeit np.linalg.eigvals(np.random.rand(100,100)) # 单行命令计时
%time # 整个格子一起计时
print("hi")
# CPU times: user 5 µs, sys: 0 ns, total: 5 µs
# Wall time: 10 µs

捕获输出内容

capture 魔法,用于捕获 stdout/err, 可以直接显示,也可以存到变量里备用:

# --------- ① capture -------- 
%%capture capt
from __future__ import print_function
import sys
print('Hello stdout')
print('and stderr', file=sys.stderr)

capt.stdout, capt.stderr # ('Hello stdout\n', 'and stderr\n')
capt.show() # Hello stdout and stderr
# --------- ② shell中捕获输出到特定文件 ------
%%bash --out output --err error
echo "hi, stdout"
echo "hello, stderr" >&2
print(error) # hi, stdout
print(output) # hello, stderr

写文件,调用文件

writefile 魔法,将后续的语句写入文件中:

%%writefile foo.py
print('Hello world') # Writing foo.py
# 调用文件内容
%run foo # Hello world, 方法①
%%script python ./foo.py # 方法②
# ----- 后台运行 -----
%%ruby --bg --out ruby_lines # 使用 --bg即可
for n in 1...10
    sleep 1
    puts "line #{n}"
    STDOUT.flush
end

显示图片

  • 【2020-8-4】两种方法,代码如下:
img_file = 'fsm.png'
# (1)pillow包
from PIL import Image
Image.open(img_file)
# (2)Ipython包
from IPython.display import Image
Image(img_file)

音频播放

使用 ipython

import IPython
IPython.display.Audio('voice_data/v02e0dg10001cddpltbc77uaeqp95020.mp3', autoplay=True)

魔法命令

Additionally, use a magic cell:

%%HTML
<video width="320" height="240" controls>
  <source src="path/to/your.mp4" type="video/mp4">
</video>

markdown

<video controls src="voice_data/v02e0dg10001cddpltbc77uaeqp95020.mp3" />

视频播放

ipython

【2022-11-17】Just do:

from IPython.display import Video

Video("test.mp4")

If you get an error No video with supported format or MIME type found, just pass embed=True to the function: Video(“test.mp4”, embed=True).

Or if you want to use the HTML element:

from IPython.display import HTML

HTML("""
    <video alt="test" controls>
        <source src="test.mp4" type="video/mp4">
    </video>
""")
# 设置 版面大小
HTML("""
<video width="320" height="240" controls>
  <source src="path/to/your.mp4" type="video/mp4">
</video>
""")
# iframe
HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/S_f2qV2_U00?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>')

魔法命令

或者使用魔法命令

%%HTML
<audio controls>
  <source src="AUDIO-FILE.mp3">
</audio>

markdown

<video controls src="path/to/video.mp4" />

大模型

【2023-8-5】JupyterAI上手初体验,魔法命令加知识库玩花活, 官方文档

Jupyter AI 是Jupyter的一个扩展工具,跟常规的Jupyter Lab extension不同,它集成了许多AIGC 接口供用户使用,如 langchain、ChatGPT、Huggingface等。能够让用户友在JupyterLab中高效地利用AI工具,从而提高工作效率。

  • 通过%%ai魔法命令,直接调用多种模型(claude, chatgpt, stablediffusion),并指定输出格式。
  • JupyterLab中提供了一个原生的聊天界面,实现了基于本地资料库的问答,以及其他基于langchain生成功能。
  • 支持多种模型 (AI21, Anthropic, Cohere, Hugging Face, OpenAI, SageMaker等)。

创建虚拟环境,专门用于学习juputerai,再进入此环境中,配置ipykernel

conda create -n py311 python=3.11 
conda activate py311
conda install ipykernel
python -m ipykernel install --user --name=py311

pip install jupyterlab~=4.0
pip install jupyter_ai

# 最后,运行juputer lab进行实战学习
jupyter lab --allow-root

进入jupyter lab,创建一个start文件夹并打开,使用py311的notebook,注意到左边插件栏下有个聊天框图标

问题

jupyter-nbextension not found

错误信息

Jupyter command `jupyter-nbextension` not found.

解决

  • 新版notebook中的,jupyter-nbextension 缺失,需要回滚
# 安装旧版
pip install notebook==6.1.5

notebook上无法显示图表

【2023-12-4】notebook上无法显示pyecharts图表

解决

# 1、获取 pyecharts-assets 项目
git clone https://github.com/pyecharts/pyecharts-assets.git

# 2、安装扩展插件
cd pyecharts-assets
# 安装并激活插件
jupyter nbextension install assets # 如果显示 jupyter-nbextension not found,需要将notebook降级到6.1.5以前
jupyter nbextension enable assets/main

# 3、配置 pyecharts 全局 HOST
# 只需要在顶部声明 CurrentConfig.ONLINE_HOST 即可
from pyecharts.globals import CurrentConfig, OnlineHostType
# OnlineHostType.NOTEBOOK_HOST 默认值为 http://localhost:8888/nbextensions/assets/
CurrentConfig.ONLINE_HOST = OnlineHostType.NOTEBOOK_HOST
# 接下来所有图形的静态资源文件都会来自刚启动的服务器
from pyecharts.charts import Bar
bar = Bar()

示例:

from pyecharts.globals import CurrentConfig, OnlineHostType
CurrentConfig.ONLINE_HOST = OnlineHostType.NOTEBOOK_HOST

# 所有图形的静态资源文件都会来自刚启动的服务器
from pyecharts.charts import Bar
bar = Bar()
bar.render_notebook()

python开发环境

  • Cython中def,cdef,cpdef的区别
    • cpdef 函数让Cython产生一个 cdef 函数(使得从Cython进行快速的函数调用)和一个 def 函数(使得我们可以从Pyhton调用)。就允许的变量类型而言,cpdef 函数具有 cdef 和 def 函数的限制。

python编译安装

  • 代码如下:
# 下载python3
src_file='https://www.python.org/ftp/python/3.8.3/Python-3.8.3.tgz'
file_name="${src_file##*/}"
install_dir=~/bin

[ -e ${file_name} ]||{
        wget ${src_file}
        echo "下载完毕..."
}&& echo "文件已存在, $file_name"
# 解压
tar zxvf ${file_name}
echo "安装目录: $install_dir"
# 安装
new_dir=${file_name%.*}
cd $new_dir
./configure --prefix=${install_dir}/python38
# 如果不设置安装目录prefix, 就会提示sudo权限
make && make install
echo "安装完毕,请设置环境变量"

# 设置环境变量
#vim ~/.bash_profile
echo "
alias python3='${install_dir}/python38/bin/python3.8'
alias pip3='${install_dir}/python38/bin/pip3'
" >> ~/.bash_profile

echo '生效'
source ~/.bash_profile

echo '检测'
python3 -c "print('hello world!')"
pip3 list

结束


支付宝打赏 微信打赏

~ 海内存知已,天涯若比邻 ~

Share

Related Posts

上一篇 Linux技能大全

下一篇 Git 学习笔记

标题:Linux技能大全

摘要:Linux使用技能总结,持续更新

标题:Git 学习笔记

摘要:代码管理工具(Git)知识点总结

Comments

--disqus--

    Content
    My Moment ( 微信公众号 )
    欢迎关注鹤啸九天