《IPython简介》

IPython是公认的现代科学计算中最重要的Python工具之一。它是一个加强版的Python交互式命令行工具,与系统自带的Python交互环境相比,IPython具有以下明显的几个特点:

  • 与Shell紧密关联,可以在IPython环境下直接执行Shell指令;
  • 可以直接绘图操作的Web GUI环境,在机器学习领域、探索数据模式、可视化数据、绘制学习曲线时,这一功能特别有用;
  • 更强大的交互功能,包括内省、Tab键自动完成、魔术命令等。


第一部分:IPython基础

1、正确安装IPython后(首先需要先安装Anaconda,如何安装,自行百度),在IPython命令行(Anaconda prompt)输入ipython即可启动IPython交互环境。

  1. (base) C:\Users\Administrator>ipython
  2. Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]
  3. Type 'copyright', 'credits' or 'license' for more information
  4. IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
  5. In [1]:
python运行

2、基本上,可以上使用Python交互环境一样使用IPython交互环境:

  1. In [1]: a=5
  2. In [2]: a+3
  3. Out[2]: 8
python运行

3、跟Python交互环境相比,IPython的输出排版更简洁、优美:

  1. In [3]: import numpy as np
  2. In [4]: data={i:np.random.randn() for i in range(8)}
  3. In [5]: data
  4. Out[5]:
  5. {0: 0.7297479153598447,
  6. 1: -0.2930247252243687,
  7. 2: 0.17482127916622928,
  8. 3: 0.9765177536261868,
  9. 4: 0.7651031974268374,
  10. 5: -0.16108735155481407,
  11. 6: 0.4821340981457667,
  12. 7: 1.0570441287244732}
python运行

4、Ipython的Tab键自动补全功能是提高效率的秘籍。例如:输入np.random.rand命令后,按Tab键,会自动显示np.random命名空间下以rand开头的所有函数。这一功能的便利性赶上了主流IDE.

  1. In [6]: import numpy as np
  2. In [7]: np.random.rand
  3. rand() random() RandomState
  4. randint() random_integers()
  5. randn() random_sample()
python运行

5、记住一些快捷键,可以让你在IPython环境下体验健步如飞的感觉。下面是IPython的快捷键:

Ctrl+A:移动光标到本行的开头;

Ctrl+E:移动光标到本行的结尾;

Ctrl+U:删除光标所在位置之前的所有字符;

Ctrl+K:删除光标所在位置之后的所有字符,包含当前光标所在的字符;

Ctrl+L:清除当前屏幕上显示的内容;

Ctrl+P:以当前输入的字符作为命令的起始字符,在历史记录里向后搜索匹配的命令;

Ctrl+N:以当前输入的字符作为命令的起始字符,在历史记录里向前搜索匹配的命令;

Ctrl+C:中断当前脚本的执行。

6、另外,IPython提供了强大的内省功能。在Python的交互环境里,只能使用help()函数来查阅内置文档,在IPython环境里可以直接在类或变量后面加上一个问号“?”来查阅文档:

  1. In [8]: np.random.randn?
  2. Docstring:
  3. randn(d0, d1, ..., dn)
  4. Return a sample (or samples) from the "standard normal" distribution.
  5. If positive, int_like or int-convertible arguments are provided,
  6. `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled
  7. with random floats sampled from a univariate "normal" (Gaussian)
  8. distribution of mean 0 and variance 1 (if any of the :math:`d_i` are
  9. floats, they are first converted to integers by truncation). A single
  10. float randomly sampled from the distribution is returned if no
  11. argument is provided.
  12. This is a convenience function. If you want an interface that takes a
  13. tuple as the first argument, use `numpy.random.standard_normal` instead.
  14. Parameters
  15. ----------
  16. d0, d1, ..., dn : int, optional
  17. The dimensions of the returned array, should be all positive.
  18. If no argument is given a single Python float is returned.
  19. Returns
  20. -------
  21. Z : ndarray or float
  22. A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
  23. the standard normal distribution, or a single such float if
  24. no parameters were supplied.
  25. ---Return to continue, q to quit---
python运行

7、在类或变量或函数后面加两个问号你“??”还可以直接查看源代码。结合型号”*“和问号”?“,还可以查询命名空间里的所有函数和对象。例如,查询np.random下面以rand开头的所有函数和对象:

  1. In [10]: np.random.rand??
  2. Docstring:
  3. rand(d0, d1, ..., dn)
  4. Random values in a given shape.
  5. Create an array of the given shape and populate it with
  6. random samples from a uniform distribution
  7. over ``[0, 1)``.
  8. Parameters
  9. ----------
  10. d0, d1, ..., dn : int, optional
  11. The dimensions of the returned array, should all be positive.
  12. If no argument is given a single Python float is returned.
  13. Returns
  14. -------
  15. out : ndarray, shape ``(d0, d1, ..., dn)``
  16. Random values.
  17. See Also
  18. --------
  19. random
  20. Notes
  21. -----
  22. This is a convenience function. If you want an interface that
  23. takes a shape-tuple as the first argument, refer to
  24. np.random.random_sample .
  25. ---Return to continue, q to quit---
python运行
  1. In [9]: np.random.rand*?
  2. np.random.rand
  3. np.random.randint
  4. np.random.randn
  5. np.random.random
  6. np.random.random_integers
  7. np.random.random_sample
python运行

从这些特性可以看出,IPython鼓励探索性编程。当你对环境还不熟悉的时候,允许通过简便快捷的方式来找到你想要的信息。

8、除此之外,IPython还提供强大魔术命令。例如,我们在当前工作目录下有一个叫hello.py的文件,然后再IPython里输入%run hello.py命令即可直接运行这个python文件。这个文件是在一个空的命名空间里运行的,并且运行之后,该文件里定义的全局变量和函数就会知道自动引用到当前IPython空间中。

In [13]: %run hello.py
python运行

9、还有一个常用的魔术命令是%timeit,可以用来快速评估代码的执行效率。例如,下面的代码用来评估一个100*100的矩阵点乘所需要运行的时间。

  1. In [14]: a=np.random.randn(100,100)
  2. In [15]: %timeit np.dot(a,a)
  3. 142 µs ± 17.3 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
python运行

10、还可以使用%who%whos命令来查看当前环境下的变量列表变量信息

  1. In [16]: %who
  2. a data msg np
python运行
  1. In [17]: %whos
  2. Variable Type Data/Info
  3. -------------------------------
  4. a ndarray 100x100: 10000 elems, type `float64`, 80000 bytes
  5. data dict n=8
  6. msg str hello ipython
  7. np module <module 'numpy' from 'C:\<...>ges\\numpy\\__init__.py'>
python运行

11、还有一些比较常用的魔术命令如下:

%quickref:显示IPython的快速参考文档;

%magic:显示所有的魔术命令及其详细文档;

%reset:删除当前环境下的所有变量和导入的模块;

%logstart:开始记录IPython里的所有命令,默认保存在当前工作目录的ipython_log.py中;

%logstop:停止记录,并关闭log文件。

12、在魔术命令后面加上“?”可以直接显示魔术命令的文档。我们来查看%reset魔术命令的文档。

  1. In [18]: %reset?
  2. Docstring:
  3. Resets the namespace by removing all names defined by the user, if
  4. called without arguments, or by removing some types of objects, such
  5. as everything currently in IPython's In[] and Out[] containers (see
  6. the parameters for details).
  7. Parameters
  8. ----------
  9. -f : force reset without asking for confirmation.
  10. -s : 'Soft' reset: Only clears your namespace, leaving history intact.
  11. References to objects may be kept. By default (without this option),
  12. we do a 'hard' reset, giving you a new session and removing all
  13. references to objects from the current session.
  14. in : reset input history
  15. out : reset output history
  16. dhist : reset directory history
  17. array : reset only variables that are NumPy arrays
  18. See Also
  19. --------
  20. reset_selective : invoked as ``%reset_selective``
python运行

13、我们经常会用import命令导入自己写的python模块,在调试过程中,修改了这个模块后,如果想让当前的修改马上起作用,必须使用reload()函数重载载入该模块。


第二部分:IPython图形界面

除了控制台环境外,IPython另外一个强大的功能是图形环境。与控制台环境相比,它有两个显著的特点:

  • 方便编写多行代码;
  • 可以直接把数据可视化,显示在当前页面下。

1、安装完Jupyter后,直接在命令行(Anaconda prompt)输入ipython notebook,启动网页版的图形编程界面。它会在命令行启动一个轻量级的Web服务器,同时用默认的浏览器打开当前目录所在的页面,在这个页面下可以直接打开某个notebook或者创建一个新的notebook。一个是以.ipynb作为后缀名的、基于json格式的文本文件。

同时,也可以直接在电脑右下角的开始里找到Anaconda的Jupyter notebook



2、我们新建一个notebook并且画一个正弦曲线,写完代码之后按Ctrl+Enter键即可运行或者选择cell里的run cell

【代码部分】

  1. # 设置 inline 方式,直接把图片画在网页上
  2. %matplotlib inline
  3. # 导入必要的库
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. # 在 [0, 2*PI] 之间取 100 个点
  7. x = np.linspace(0, 2 * np.pi, num=100)
  8. # 计算这 100 个点的正弦值,并保存在变量 y
  9. y = np.sin(x)
  10. # 画出 x, y 即是我们的正弦曲线
  11. plt.plot(x, y)
python运行

【显示部分】

3、IPython notebook有两个模式,一个是编辑模式,可以直接在这个cell上写代码;另一个是命令模式,即输入的按键作为命令,而不是作为文本处理。按Ctrl+M快捷键在命令模式和编辑模式之间切换。

命令模式快捷键:

  • J:焦点上移一个cell;
  • K:焦点下移一个cell;
  • A:在当前cell的上面插入一个新的cell;
  • B:在当前cell的下面插入一个新的cell;
  • DD:连续按两下D键,删除当前cell。

编辑模式快捷键:

  • Ctrl+Enter:执行当前的cell代码;
  • Shift+Enter:执行当前的cell代码,并把焦点移到下一个cell处,如果没有下一个cell则会自动创建一个新的cell。


参考书籍:

《scikit-learn机器学习常用算法原理及编程实践》 黄永昌

登录后您可以享受以下权益:

×
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他
点击体验
DeepSeekR1满血版
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回顶部