IPython是公认的现代科学计算中最重要的Python工具之一。它是一个加强版的Python交互式命令行工具,与系统自带的Python交互环境相比,IPython具有以下明显的几个特点:
- 与Shell紧密关联,可以在IPython环境下直接执行Shell指令;
- 可以直接绘图操作的Web GUI环境,在机器学习领域、探索数据模式、可视化数据、绘制学习曲线时,这一功能特别有用;
- 更强大的交互功能,包括内省、Tab键自动完成、魔术命令等。
第一部分:IPython基础
1、正确安装IPython后(首先需要先安装Anaconda,如何安装,自行百度),在IPython命令行(Anaconda prompt)输入ipython即可启动IPython交互环境。
- (base) C:\Users\Administrator>ipython
- Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]
- Type 'copyright', 'credits' or 'license' for more information
- IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
-
- In [1]:
python运行
2、基本上,可以上使用Python交互环境一样使用IPython交互环境:
- In [1]: a=5
-
- In [2]: a+3
- Out[2]: 8
python运行
3、跟Python交互环境相比,IPython的输出排版更简洁、优美:
- In [3]: import numpy as np
-
- In [4]: data={i:np.random.randn() for i in range(8)}
-
- In [5]: data
- Out[5]:
- {0: 0.7297479153598447,
- 1: -0.2930247252243687,
- 2: 0.17482127916622928,
- 3: 0.9765177536261868,
- 4: 0.7651031974268374,
- 5: -0.16108735155481407,
- 6: 0.4821340981457667,
- 7: 1.0570441287244732}
python运行
4、Ipython的Tab键自动补全功能是提高效率的秘籍。例如:输入np.random.rand命令后,按Tab键,会自动显示np.random命名空间下以rand开头的所有函数。这一功能的便利性赶上了主流IDE.
- In [6]: import numpy as np
-
- In [7]: np.random.rand
- rand() random() RandomState
- randint() random_integers()
- 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环境里可以直接在类或变量后面加上一个问号“?”来查阅文档:
- In [8]: np.random.randn?
- Docstring:
- randn(d0, d1, ..., dn)
-
- Return a sample (or samples) from the "standard normal" distribution.
-
- If positive, int_like or int-convertible arguments are provided,
- `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled
- with random floats sampled from a univariate "normal" (Gaussian)
- distribution of mean 0 and variance 1 (if any of the :math:`d_i` are
- floats, they are first converted to integers by truncation). A single
- float randomly sampled from the distribution is returned if no
- argument is provided.
-
- This is a convenience function. If you want an interface that takes a
- tuple as the first argument, use `numpy.random.standard_normal` instead.
-
- Parameters
- ----------
- d0, d1, ..., dn : int, optional
- The dimensions of the returned array, should be all positive.
- If no argument is given a single Python float is returned.
-
- Returns
- -------
- Z : ndarray or float
- A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
- the standard normal distribution, or a single such float if
- no parameters were supplied.
-
- ---Return to continue, q to quit---
python运行
7、在类或变量或函数后面加两个问号你“??”还可以直接查看源代码。结合型号”*“和问号”?“,还可以查询命名空间里的所有函数和对象。例如,查询np.random下面以rand开头的所有函数和对象:
- In [10]: np.random.rand??
- Docstring:
- rand(d0, d1, ..., dn)
-
- Random values in a given shape.
-
- Create an array of the given shape and populate it with
- random samples from a uniform distribution
- over ``[0, 1)``.
-
- Parameters
- ----------
- d0, d1, ..., dn : int, optional
- The dimensions of the returned array, should all be positive.
- If no argument is given a single Python float is returned.
-
- Returns
- -------
- out : ndarray, shape ``(d0, d1, ..., dn)``
- Random values.
-
- See Also
- --------
- random
-
- Notes
- -----
- This is a convenience function. If you want an interface that
- takes a shape-tuple as the first argument, refer to
- np.random.random_sample .
- ---Return to continue, q to quit---
python运行
- In [9]: np.random.rand*?
- np.random.rand
- np.random.randint
- np.random.randn
- np.random.random
- np.random.random_integers
- 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的矩阵点乘所需要运行的时间。
- In [14]: a=np.random.randn(100,100)
-
- In [15]: %timeit np.dot(a,a)
- 142 µs ± 17.3 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
python运行
10、还可以使用%who或%whos命令来查看当前环境下的变量列表和变量信息。
- In [16]: %who
- a data msg np
python运行
- In [17]: %whos
- Variable Type Data/Info
- -------------------------------
- a ndarray 100x100: 10000 elems, type `float64`, 80000 bytes
- data dict n=8
- msg str hello ipython
- 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魔术命令的文档。
- In [18]: %reset?
- Docstring:
- Resets the namespace by removing all names defined by the user, if
- called without arguments, or by removing some types of objects, such
- as everything currently in IPython's In[] and Out[] containers (see
- the parameters for details).
- Parameters
- ----------
- -f : force reset without asking for confirmation.
- -s : 'Soft' reset: Only clears your namespace, leaving history intact.
- References to objects may be kept. By default (without this option),
- we do a 'hard' reset, giving you a new session and removing all
- references to objects from the current session.
- in : reset input history
- out : reset output history
- dhist : reset directory history
- array : reset only variables that are NumPy arrays
- See Also
- --------
- 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。
【代码部分】
- # 设置 inline 方式,直接把图片画在网页上
- %matplotlib inline
- # 导入必要的库
- import numpy as np
- import matplotlib.pyplot as plt
-
- # 在 [0, 2*PI] 之间取 100 个点
- x = np.linspace(0, 2 * np.pi, num=100)
- # 计算这 100 个点的正弦值,并保存在变量 y
- y = np.sin(x)
- # 画出 x, y 即是我们的正弦曲线
- 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机器学习常用算法原理及编程实践》 黄永昌