18 个 Jupyter Notebook 小技巧,帮助你快速腾飞

Python编辑器:Jupyter Notebook 点赞 + 关注 + 收藏 = 学会了 什么是 Jupyter Notebook ? 在 《Python 快速入门篇》 里我提到了3个编辑器,其中一个是 Jupyter Notebook。 Jupyter Notebook 是一个基于网页的交互式计算环境,是大多数数据分析师喜欢的工具。它可以用来写代码、运行代码、可视化数据,甚至可以当笔记本使用。 相比起 VS Code 和 PyCharm,... 阅读详情

Jupyter Notebook 是干嘛的就不再过多介绍了,这篇文章收集了一些顶级的 Jupyter Notebook 技巧,可以让你迅速成为一个 Jupyter 超级使用者!

作为一款完全免费的产品,它的身上有太多值得探索的内容了,这里整理了28个,希望能够对你有所帮助。

1、快捷键

任何重度用户应该都知道,键盘快捷键的有效使用可以节省大量时间。Jupyter 在顶部的菜单下存储了一个 keybord 快捷键列表:Help>Keyboard shortcuts,或者在命令模式下按H键也可以调出。我们每次更新 Jupyter 时都需要检查一下快捷键的情况,因为很多时候总是会添加更多的快捷方式。

另一种访问快捷键的方法,也是学习快捷键的一种简便方法,就是使用命令面板:Cmd+Shift+P(在Linux和Windows上是Ctrl+Shift+P)。这个对话框可帮助我们按名称运行任何命令—如果我们不知道某个操作的键盘快捷键,或者想要执行的操作没有键盘快捷键,那么该对话框将是非常有用。它的功能类似于 Mac 上的 Spotlight 搜索,一旦我们开始使用它,你就会依赖它,以至于会想没有它你会怎么生活!

下面是一些我个人比较喜欢的快捷键:

Esc 进入命令模式

在命令模式下:

  • A要在当前单元格上方插入新单元格,B将在下面插入新单元格。

  • M要将当前单元格更改为标记,Y将其更改为代码

  • D+D(按两次键)删除当前单元格

Enter将使我们从命令模式返回到给定单元格的编辑模式。

Shift+Tab将显示刚输入代码单元的对象的Docstring(文档)——可以继续按此键切换以循环使用几种文档模式。

Ctrl+Shift+-将当前单元格从光标所在的位置拆分为两个。

Esc+F查找并替换代码,但不是输出。

Esc+O切换单元格输出。

选择多个单元格:

  • Shift+J或Shift+Down选择下一个单元格,也可以使用Shift+K或Shift+Up选择向上一个单元格。

  • 一旦我们选择了多个单元格,就可以对它们进行批量的删除/复制/剪切/粘贴/运行,这个功能在需要修改部分脚本是是很有帮助的。

  • 可以使用Shift+M合并多个单元格。

2、漂亮的显示变量

我们都知道,通过使用变量名或语句的未赋值输出完成Jupyter单元格,Jupyter将显示该变量,而不需要print语句。这在处理数据帧时特别有用,因为输出被整齐地格式化为一个表。

但是鲜为人知的是,我们可以修改一个 ast_note_interactivity 选项,使Jupyter对自己行中的任何变量或语句执行此操作,这样我们就可以一次看到多个语句的值。

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

from pydataset import data
quakes = data('quakes')
quakes.head()
quakes.tail()

如果要为所有Jupyter实例(笔记本和控制台)设置这个行为,只需创建一个文件~/.ipython/profile_default/ipython_config.py,通过下面的代码实现

c = get_config()

# Run all nodes interactively
c.InteractiveShell.ast_node_interactivity = "all"

3、文档的简单链接

在“帮助”菜单中,可以找到指向常用库(包括NumPy、Pandas、SciPy和Matplotlib)的联机文档链接。

但是我们也应该知道,在库、方法或变量前面加上?,也可以访问Docstring以快速参考语法。

?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中绘制图片

  • matplotlib,用%matplotlib inline激活–大部分情况下,使用matplotlib绘图是实际上的标准

  • %matplotlib notebook提供了交互性,但是速度可能有点慢,因为所有的渲染都是在服务器端完成的。

  • Seaborn是建立在Matplotlib之上的,它使得建造更具吸引力的图片变得更加容易。只需导入Seaborn,matplotlib绘图就变得“更漂亮”,无需任何代码修改。

  • mpld3为matplotlib代码提供了可选的呈现器(使用d3)。很好,可以选择尝试下。

  • bokeh是一个更好的选择,可以建立互动的场景。

  • ploy.ly可以绘制一些很棒的动态图表-虽然曾经是一个付费服务,但是现在已经开源了。

  • Altair是一个相对较新的Python可视化库。很容易使用,并且可以生成非常好看的绘图,但是定制这些绘图的功能远不如Matplotlib强大。

5、IPython 魔法命令行

上面看到的%matplotlib就是IPython魔术命令的一个示例,基于IPython内核,Jupyter可以访问IPython内核中的所有魔法,它们可以让我们更轻松的使用 Jupyter!

# This will list all magic commands
%lsmagic

Available line magics:
%alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode 
Available cell magics:%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile 
Automagic is ON, % prefix IS NOT needed for line magics.

6、IPython 魔法-%env 设置环境变量

我们可以管理notebook的环境变量,而无需重新启动jupyter服务器进程。有些库是(比如theano)使用环境变量来控制行为的,%env 就是最方便的方法。

# Running %env without any arguments
# lists all environment variables# The line below sets the environment
# variable
%env OMP_NUM_THREADS%env OMP_NUM_THREADS=4

env: OMP_NUM_THREADS=4

7、IPython 魔法-%run 执行Python代码

%run可以从.py文件执行python代码——这是一个有很好方法,但是却很少有人知道,它还可以执行其他jupyter notebook,这也非常有用。

需要注意的是,使用%run与导入python模块不同。

# this will execute and show the output from
# all code cells of the specified notebook
%run ./two-histograms.ipynb

8、IPython 魔法-%load 从外部脚本插入代码

这个魔法语言,可以用外部脚本替换单元格的内容,可以使用计算机上的文件作为源,也可以使用URL。

# Before Running
%load ./hello_world.py

# After Running
# %load ./hello_world.py
if __name__ == "__main__":
 print("Hello World!")

Hello World!

9、IPython 魔法-%store 在notebook之间传递变

%store命令允许我们在两个不同的notebook之间传递变量。

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中

%store -r data
print(data)

this is the string I want to pass to different notebook

10、IPython 魔法-%who 列出全局范围的所有变量

不带任何参数的%who命令将列出全局范围中存在的所有变量,传递类似str的参数将只列出该类型的变量。

one = "for the money"
two = "for the show"
three = "to get ready now go cat go"
%who str

one three two

11、IPython 魔法-计时功能

有两个IPython魔术命令对计时很有用–%%time和%timeit,当我们有一些慢代码需要执行并且试图找出问题所在的时候,这就特别方便了。

%%time会给你关于代码里一次代码运行的信息。

%%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模块,该模块运行一条语句100000次(默认情况下),然后提供最快三次的平均值。

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

12、IPython 魔法-%%writefile和%pycat 导出单元格的内容/显示外部脚本的内容

使用%%writefile将该单元格的内容保存到外部文件中,%pycat的作用正好相反,它(在弹出窗口中)可以显示外部文件的内容。

%%writefile

%%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

%%pycat

%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)

13、IPython 魔法-%prun 显示程序在每个函数中花费的时间

使用%prun statement_name将生产一个有序表,显示在语句中调用每个内部函数的次数、每次调用所占用的时间以及函数的所有运行的累计时间。

%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 :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 :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 :1()
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}

14、IPython 魔法-使用%pdb进行调试

Jupyter有自己的Python调试器(pdb)接口,这样就可以进入函数内部并调查那里发生了什么。

%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)
in ()
5 raise NotImplementedError()
6
----> 7 pick_and_take()
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:

> (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>

15、执行Shell命令

从notebook内部执行shell命令很容易,可以使用此选项检查工作文件夹中的可用数据集

!ls *.csv

nba_2016.csv titanic.csv pixar_movies.csv whitehouse_employees.csv

检查安装的库

!pip install numpy !pip list | grep pandas

Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages pandas (0.18.1)

16、使用LaTeX格式化

在markdown单元格中写入LaTeX时,将使用MathJax将其呈现为公式。

$P(A mid B) = frac{P(B mid A)P(A)}{P(B)}$

我们要时刻谨记,MarkDown 是 Jupyter 的非常重要的一部分,一定要好好利用

17、在一个notebook中使用不同的kernel运行代码

如果需要,可以将多个内核中的代码合并到一个notebook中。

只需在每个要使用内核的单元格的开头使用ipython magics和内核名称:

  • %%bash

  • %%HTML

  • %%python2

  • %%python3

  • %%ruby

  • %%perl

%%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

18、在同一个notebook上运行R和Python

最好的解决方案是安装rpy2,这可以通过pip轻松完成:

pip install rpy2

接下来就是同时使用两种语言了

%load_ext rpy2.ipython
%R require(ggplot2)


array([1], dtype=int32)

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]
})

%%R -i df ggplot(data = df) + geom_point(aes(x = X, y= Y, color = Letter, size = Z))

好了,今天的分享就到这里,还不给个“在看”吗

推荐阅读:入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|年度爆款文案1).卧槽!Pdf转Word用Python轻松搞定!2).学Python真香!我用100行代码做了个网站,帮人PS旅行图片,赚个鸡腿吃3).首播过亿,火爆全网,我分析了《乘风破浪的姐姐》,发现了这些秘密 4).80行代码!用Python做一个哆来A梦分身 5).你必须掌握的20个python代码,短小精悍,用处无穷 6).30个Python奇淫技巧集 7).我总结的80页《菜鸟学Python精选干货.pdf》,都是干货 8).再见Python!我要学Go了!2500字深度分析!9).发现一个舔狗福利!这个Python爬虫神器太爽了,自动下载妹子图片
点阅读原文,领AI全套资料!
机器学习入门指南:Jupyter Notebook实战 对于机器学习工程师而言,他们更擅长的是算法、模型、数据探索的工作,而对于工程化的能力则并不是其擅长的工作。Jupyter Notebook生成PMML文件1​​​​​​​。Jupyter Notebook生成PMML文件2​​​​​​​。PySpark Notebook建模 -折线图​​​​​​​。TensorFlowNotebook建模​​​​​​​。R Notebook建模 - 散点图​​​​​​​。PySpark Notebook建模​​​​​​​。R Notebook获取训练数据集​​​​​​​。 阅读详情

相关推荐

基于PDF文档结构的数字隐写

PDF隐写

xiongshivigor的博客 1426

jupyter notebook和jupyter lab中的常用快捷键小结(自用)

jupyter notebook和jupyter lab中的常用快捷键小结(自用)

小坏蛋的博客 5597

Qt+OpenGL+Cesium三件套:打造高性能3D GIS桌面应用的5个关键点

本文深入探讨了如何利用Qt、OpenGL和Cesium数据规范构建高性能桌面级3D GIS应用。文章聚焦于五个关键点:架构选型、OpenGL渲染优化、3D Tiles数据解析与调度、内存与多线程管理,以及高级特性实现,旨在帮助开发者在C++生态中打造不依赖网络、运算能力更强的重型3D地理信息客户端。

weixin_28197941的博客 381

jupyter常用的方法以及快捷键

选中状态 蓝色 按enter 进入编辑状态编辑状态 绿色 按Esc 进入选中状态Code模式运行是运行代码Markdown模式运行是进入预览状态 - - - 是文本格式的一种精简的语法形式Raw NBConvert 是默认文本状态 - - - 输入什么样 展示什么样Y - - - 切换code模式M - - - 切换Markdown模式Shift + Enter 运行选中单元格,并且在下方选中(新增)一个单元格Alt + Enter 运行当前单元格,并在下面新增一个单元格。

weixin_64729620的博客 1952

SKUA-GOCAD入门教程-第八节 线的创建与编辑7和8

本文介绍了曲线编辑操作的主要功能,包括曲线部分和区域的管理操作。在曲线部分操作方面,详细说明了如何合并、删除、移动和过滤曲线部分,支持精确或带公差的合并方式。在曲线区域操作方面,阐述了保留/删除区域点、移动区域点、保留/删除区域线段等操作。此外还介绍了节点连接功能,包括新增/删除连接、端点连接以及为曲线赋予地质特征的方法。

江洋大葱的博客 390

【4. BSP开发指南 - [4.6. 安全启动使用说明]】

【4. BSP开发指南 - [4.6. 安全启动使用说明]】

Sugar_wolf的博客 276

【python】jupyter notebook的快捷键

Jupyter Notebook 是一个非常受欢迎的交互式计算环境,它允许用户创建和共享包含实时代码、方程、可视化和文本的文档。总之,Jupyter Notebook 的交互性、多语言支持、丰富的可视化功能和易于共享的特点使其成为数据科学家、研究人员和教育工作者的理想选择。这使得 Jupyter Notebook 成为一个很好的教学工具,便于创建包含可读的解释和实时代码示例的教程和课程材料。用户可以直接在 Notebook 中创建高质量的图表和可视化,并随着代码的更改实时更新。上使用相同的工具和工作流程。

hmywillstronger的博客 5819

【实战教程】OpenClaw接入MySQL数据库实战指南

本文介绍了在虚拟机Ubuntu中访问宿主机Win11中MySQL数据库的配置方法,重点包括创建远程用户、权限配置和安全设置。首先在MySQL中创建具有只读权限的用户并刷新权限,然后调整服务器设置允许远程连接。文章还提供了某金融机构财富管理系统的数据库设计方案,包含理财产品表、客户表和份额表的核心结构,其中金额字段使用DECIMAL类型确保精度,并设置唯一键约束。文末强调测试环境配置完成后应恢复安全更新模式以保障生产环境安全。

海兰 8701

Jupyter Notebook的27个窍门,技巧和快捷键

这篇文章是基于一篇最初出现在Alex Rogozhnikov的博客上的文章 Jupyther notebook ,也就是一般说的 Ipython notebook,是一个可以把代码、图像、注释、公式和作图集于一处,从而实现可读性分析的一种灵活的工具。 Jupyter延伸性很好,支持多种编程语言,可以很轻松地安装在个人电脑或者任何服务器上——只要有ssh或者http接入就可以啦。最棒的一点是...

huobanjishijian的专栏 469

【A2DP】规范精讲[1]: 深入解析A2DP协议的核心架构

在蓝牙技术发展的早期阶段,音频传输主要通过SCO(同步面向连接)链路实现,这种设计主要针对语音通信,音质有限且功能单一。随着人们对无线高质量音频需求的增长,​​Advanced Audio Distribution Profile (A2DP)​​ 应运而生,成为蓝牙音频传输的技术基石。

byte轻骑兵的技术小窝 1万+

【Windows Server 2019】组策略的配置与管理——理论基础

博文介绍了组策略的定义,作用和分类。组策略包括计算机配置和用户配置;组策略又分为为基于本地的组策略和基于AD(活动目录)的域组策略。并说明了不同组策略发生冲突时默认的规则。

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 1万+

jupyter中的魔法函数

jupyter 魔法函数

m0_58625397的博客 742

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

超好用,18 个 Jupyter Notebook 使用技巧助你快速腾飞

Jupyter Notebook 是干嘛的就不再过多介绍了,这篇文章收集了一些顶级的 Jupyter Notebook 技巧,可以让你迅速成为一个 Jupyter 超级使用者!作为一款完全免费的产品,它的身上有太多值得探索的内容了,这里整理了28个,希望能够对你有所帮助。1、快捷键任何重度用户应该都知道,键盘快捷键的有效使用可以节省大量时间。Jupyter 在顶部的菜单下存储了一个 keybord 快捷键列表:Help>Keyboard shortcuts,或者在命令模式下按H键也可以调出。我们每次更

Python数据挖掘 2866

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Python的魔法函数(magic methods)或者特殊方法(Dunder methods)

决定梳理这个内容是因为一个课程, 课程ppt:https://github.com/minitorch/slides 使用的时候,下载下来,把index.html文件拖到浏览器,然后方向键下键,ppt以网页形式播放) 1. Python语言的魔法函数 简单来说,在python中,任何以__开头和结尾的函数,都是魔法函数,例如:__init__就是一种魔法函数。 它可以重载默认函数的行为 特殊方法以两个下划线开始,两个下划线结尾。于是乎特殊方法也叫双下方法(dunder method)。dunder,即

啷个哩个啷 5247

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

13. Jupyter Notebook介绍、安装及使用

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取哈)

m0_59163425的博客 1万+

Jupyter详细功能介绍

一、简介 Jupyter Notebook(此前被称为 IPython notebook)是一个交互式笔记本,支持运行 40 多种编程语言。 Jupyter Notebook是一个开源的Web应用程序,允许用户创建和共享包含代码、方程式、可视化和文本的文档,支持实时代码,数学方程,可视化和 markdown。 1、具有以下用途:数据清理和转换、数值模拟、统计建模、数据可视化、机器学习等等。 2、具...

qq_40290810的博客 1万+

Jupyter Notebook基本操作(使用快捷键)

转自:https://blog.youkuaiyun.com/QimaoRyan/article/details/76022038#23编辑模式快捷键   注:在Jupyter Notebook的主界面上Help ---&gt; Keyboard Shortcut 即可看到所有快捷键,并且进行编辑    Jupyter Notebook基本操作   1.Jupyter Notebook服务启动与停...

breeze_blows的博客 2万+

Jupyter Notebook是什么及使用

Jupyter项目是一个非盈利的开源项目,源于2014年的python项目,Juptter Notebook,原名IPython Notbook,是IPython的加强网页版,一个开源web应用程序名字源自Julia、Python和R是一款程序员和科学工作者的编程/文档/笔记/展示软件.ipynb文件格式是用于计算型叙述的JSON文档格式的正式规范Juptyter项目旨在开发跨几十中编程语言的开源软件,开放标准和用于交互式计算的服务。

NeilNiu 4742

Jupyter中的魔法函数

Jupyter的魅力之处,除了体现在能提供丰富多彩的格式化文本显示,还体现在它提供了很多好用的函数。这些函数如同有魔力一般,故也被称为魔法函数(Magic Function)。所谓魔法函数,实际上是IPython预先定义好的具备特定功能的函数被放到Jupyter中使用罢了。 请注意,这是IPython特有的函数,并非Python的内置函数,因此脱离IPython的使用环境(如使用Pycharm或Python自带的IDLE开发环境等),这些函数是无法被解析运行的。 在图1-22中,第14行和第16行就分别

玉来愈宏的随笔 5891

jupyter 魔法函数

https://blog.youkuaiyun.com/kepengs/article/details/84076008

studyvcmfc的专栏 253

jupyter单元格魔法函数

IPython中的单元格魔法 IPython拥有一些被称为"魔法"(magic)的命令,这些命令独立于Python语法,且用户可扩展出新的命令。"魔法"的设计初衷在于可以在IPython中交互式地执行一些命令(比如执行某些系统命令),所以它遵循了命令行的一些惯例,比如:使用空格来分隔参数,'-'来表示选项等。 "魔法"有两种: 行魔法(line magic): 以"%"为前缀,且整个命令(包...

kepengs的博客 3536

Jupyter Notebook介绍、安装及使用教程

原博文一、什么是Jupyter Notebook?1. 简介Jupyter Notebook是基于网页的用于交互计算的应用程序。其可被应用于全过程计算:开发、文档编写、运行代码和展示结果。——Jupyter Notebook官方介绍简而言之,Jupyter Notebook是以网页的形式打开,可以在网页页面中直接编写代码和运行代码,代码的运行结果也会直接在代码块下显示的程序。如在编程过程中需要编写...

u011511601的专栏 3万+
上一篇: GitHub 上 25 个 Python 学习资源,墙裂推荐!
下一篇: 关于Python3.9,你不可不知的4个新特性
菜鸟学Python
博客等级 码龄9年 8095粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值