SciPy定義了一些用于計(jì)算點(diǎn)集之間距離的有用函數(shù)。
函數(shù)scipy.spatial.distance.pdist計(jì)算給定集合中所有點(diǎn)對(duì)之間的距離:
import numpy as np
from scipy.spatial.distance import pdist, squareform
# Create the following array where each row is a point in 2D space:
# [[0 1]
#? [1 0]
#? [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
# and d is the following array:
# [[ 0.? ? ? ? ? 1.41421356? 2.23606798]
#? [ 1.41421356? 0.? ? ? ? ? 1.? ? ? ? ]
#? [ 2.23606798? 1.? ? ? ? ? 0.? ? ? ? ]]
d = squareform(pdist(x, 'euclidean'))
print(d)
Matplotlib
Matplotlib是一個(gè)繪圖庫(kù)。本節(jié)簡(jiǎn)要介紹 matplotlib.pyplot 模塊微王,該模塊提供了類(lèi)似于MATLAB的繪圖系統(tǒng)。
繪制
matplotlib中最重要的功能是plot贾铝,它允許你繪制2D數(shù)據(jù)的圖像嘉抓。這是一個(gè)簡(jiǎn)單的例子:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x,y_sin)
plt.plot(x,y_cos)
plt.xlabel('x axis label')-橫坐標(biāo)
plt.ylabel('y axis label')-縱坐標(biāo)
plt.title('Sine and Cosine')-標(biāo)題
plt.legend(['Sine','Cosine'])-標(biāo)識(shí)
plt.show()
子圖
https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot
你可以使用subplot函數(shù)在同一個(gè)圖中繪制不同的東西。 這是一個(gè)例子:
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)-(2,1,2)一起在下方圖中
# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)? -(2胜茧,1,1)一起在上方圖中
plt.plot(x, y_cos)
plt.title('Cosine')
# Show the figure.
plt.show()
圖片
你可以使用 imshow 函數(shù)來(lái)顯示一張圖片仇味。 這是一個(gè)例子:
import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
img = imread('assets/cat.jpg')
img_tinted = img * [1, 0.95, 0.9]
# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)
# Show the tinted image
plt.subplot(1, 2, 2)
# A slight gotcha with imshow is that it might give strange results
# if presented with data that is not uint8. To work around this, we
# explicitly cast the image to uint8 before displaying it.
plt.imshow(np.uint8(img_tinted))
plt.show()