Python 常用库的使用
本文于 260602,从 站内文章这片文章 解耦而来,并融合新的内容。
NumPy

NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
快速开始:NumPy quickstart — NumPy v1.23.dev0 Manual
要点
常用指令:
1 | A = np.array([[1,2],[3,4]]) |
数学上将一维数组称为向量,将二维数组称为矩阵。另外,可以将一般化之后的向量或矩阵等统称为张量(tensor)。本书基本上将二维数组称为「矩阵」,将三维数组及三维以上的数组称为「张量」或「多维数组」。
因为「广播」机制,形状不同的数组之间也可以进行运算。


获取元素的方法:
1 | X = X.flatten() # 将X转换为一维数组 |
下面的代码意味着:
- 生成 1000 个 服从正态分布的随机数
loc=0.5:平均值是 0.5scale=0.4:标准差 0.4
1 | # make up some data in the open interval (0, 1) |
矩阵乘法(点积):
1 | A = np.array([[1,2], [3,4]]) |
Pillow

Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors.
文档:Pillow — Pillow (PIL Fork) 8.4.0 documentation
经验教训
1 | result = np.array(result, dtype=np.uint8).reshape(largeH, largeW).transpose() |
使用数组转变成图片时,必须要指明数组中的数据类型,否则生成错误图片。
Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Matplotlib makes easy things easy and hard things possible.
官网主页:Matplotlib — Visualization with Python
基本使用
绘制 sin 函数曲线:
1 | import numpy as np |
继续增加 cos 曲线:
1 | import numpy as np |
显示图像:
1 | import matplotlib.pyplot as plt |
经验教训
记得 plt.show()
1 | plt.title(r'$\sigma_i=15$') |
本文参考
- 本科时的笔记
- 《深度学习入门:基于 Python 的理论与实现》





