摘要生成中...
AI 摘要
Hunyuan-lite
解耦焕新

本文于 260602,从 站内文章这片文章 解耦而来,并融合新的内容。

NumPy

image.png

NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

快速开始:NumPy quickstart — NumPy v1.23.dev0 Manual

要点

常用指令:

1
2
3
4
5
6
7
>>> A = np.array([[1,2],[3,4]])
>>> A.shape # 查看 A 的形状
(2, 2)
>>> A.dtype # 查看元素的数据类型
dtype('int64')
>>> np.ndim(A) # 查看维度
2

数学上将一维数组称为向量,将二维数组称为矩阵。另外,可以将一般化之后的向量或矩阵等统称为张量(tensor)。本书基本上将二维数组称为「矩阵」,将三维数组及三维以上的数组称为「张量」或「多维数组」。

因为「广播」机制,形状不同的数组之间也可以进行运算。

image0016920260602.jpg

image00170062023e21d3.jpg

获取元素的方法:

1
2
3
4
5
6
7
8
9
10
>>> X = X.flatten()         # 将X转换为一维数组
>>> print(X)
[51 55 14 19 0 4]
>>> X[np.array([0, 2, 4])] # 获取索引为0、2、4的元素
array([51, 14, 0])

>>> X > 15 # 对NumPy数组使用不等号运算符等,结果会得到一个布尔型的数组。
array([ True, True, False, True, False, False], dtype=bool)
>>> X[X>15] # 使用这个布尔型数组取出了数组的各个元素(取出True对应的元素)。
array([51, 55, 19])

下面的代码意味着:

  • 生成 1000 个 服从正态分布的随机数
  • loc=0.5:平均值是 0.5
  • scale=0.4:标准差 0.4
1
2
3
# make up some data in the open interval (0, 1)
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)] # 布尔索引

矩阵乘法(点积):

1
2
3
4
5
>>> A = np.array([[1,2], [3,4]])
>>> B = np.array([[5,6], [7,8]])
>>> np.dot(A, B)
array([[19, 22],
[43, 50]])

Pillow

image.png

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
2
result = np.array(result, dtype=np.uint8).reshape(largeH, largeW).transpose()
imageLargeCat = Image.fromarray(result, mode='L')

使用数组转变成图片时,必须要指明数组中的数据类型,否则生成错误图片。

Matplotlib

image.png

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
2
3
4
5
6
7
8
9
10
import numpy as np
import matplotlib.pyplot as plt

# 生成数据
x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到6的数据
y = np.sin(x)

# 绘制图形
plt.plot(x, y)
plt.show()

继续增加 cos 曲线:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np
import matplotlib.pyplot as plt

# 生成数据
x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到6的数据
y1 = np.sin(x)
y2 = np.cos(x)

# 绘制图形
plt.plot(x, y1, label="sin")
plt.plot(x, y2, linestyle = "--", label="cos") # 用虚线绘制
plt.xlabel("x") # x轴标签
plt.ylabel("y") # y轴标签
plt.title('sin & cos') # 标题
plt.legend()
plt.show()

显示图像:

1
2
3
4
5
6
import matplotlib.pyplot as plt
from matplotlib.image import imread
img = imread('lena.png') # 读入图像(设定合适的路径!)
plt.imshow(img)

plt.show()

经验教训

记得 plt.show()

1
2
3
4
plt.title(r'$\sigma_i=15$')
# The r preceding the title string is important
# -- it signifies that the string is a raw string
# and not to treat backslashes as python escapes.

本文参考

  • 本科时的笔记
  • 《深度学习入门:基于 Python 的理论与实现》