记录 Python 中使用过的有用代码,以后应该还用的上。
平滑对比曲线图
1 | import matplotlib.pyplot as plt |
对比柱状图
1 | def comparision_histogram(self): |
设置图例位置
1 | plt.legend(loc = 'upper right') |
plot 全局设定
1 | plt.rcParams['figure.dpi'] = 300 |
转换 array: reshape()
1 | import numpy as np |
计算向量距离: pairwise_distances()
1 | from sklearn.metrics import pairwise_distances |
计算向量距离: cdist(), pdist()
在 scripy.spatial.distance
库下。
cdist()
用于两个数组(矩阵)之间,pdist()
用于一个数组中。
cdist()
:X = m * n, Y = a * n, res =
cdist(X, Y)
= m * a可以看作是 X 为 m 个 n 维向量,Y 为 a 个 n 维向量,
cdist()
求 X 中每个向量到 Y 中每个向量的距离,可以用来计算分离度。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15X=np.array([[9,3,7],[5,7,9]])
# 即便是 X 中只有一组数据跟 Y 的两组数据分别求欧氏距离,
# 也需要写成二维数组的形式,如 X=np.array([[5,3,6]])
Y = np.array([[4,6,5],[4,2,3]])
res = cdist(X, Y, metric='euclidean')
print(res)
# output
[[a b]
[c d]]
# a 为向量 [9, 3, 7] 到 [4, 6, 5] 的距离
# b 为向量 [9, 3, 7] 到 [4, 2, 3] 的距离
# c 为向量 [5, 7, 9] 到 [4, 6, 5] 的距离
# d 为向量 [5, 7, 9] 到 [4, 2, 3] 的距离pdist()
andsquareform()
:X = m * n, res =
pdist(X)
= m * m, 其中 res 为对称距离矩阵,对角线元素为 0。pdist()
可以看作是求 X 中 m 个 n 维向量之间的距离,可以用来计算内聚度。squareform()
和pdist()
配套使用,用来压缩矩阵(或者还原矩阵)。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16x = np.array([[ 0, 2, 3, 4],
[ 2, 0, 7, 8],
[ 3, 7, 0, 12],
[ 4, 8, 12, 0]])
y = dist.squareform(x)
print(y)
# output
[ 2, 3, 4, 7, 8, 12]
x = dist.squareform(y)
print(x)
# output
[[ 0, 2, 3, 4],
[ 2, 0, 7, 8],
[ 3, 7, 0, 12],
[ 4, 8, 12, 0]]
从列表或 array 中随机采样: random.choice()
1 | import numpy as np |
从 array 中选取特定行
1 | import numpy as np |
去重: unique()
1 | import numpy as np |
可遍历对象组合为索引序列: enurmerate()
1 | seasons = ['Spring', 'Summer', 'Fall', 'Winter'] |
numpy 初始化生成相同元素值的数组
使用 numpy.full()
函数
1 | print(np.full(3, 100, dtype = np.int32)) |
numpy 数组添加一列/一行
使用 numpy.insert()
函数
1 | import numpy as np |