# -*- coding: utf-8 -*-
"""
numpy:矩陣或者數組相減
"""
import numpy as np
if __name__ == '__main__':
feature = np.array([2,3,5])
center = np.array([1,2,3])
print("原始數據維度:")
print(feature.shape)
print(center.shape)
result = feature - center
print("維度相同的減法:")
print(result)
print('\n******************\n')
feature2 = np.array([[2,3,5]])
center2 = np.array([[1,2,3],[2,3,4]])
print("擴充維度:")
print(feature2.shape)
print(center2.shape)
result2 = feature2 - center2
print("維度不同的減法:")
print(result2)
print(result2.shape)
#產生這種結果的原因:是因爲由於維度不同,在計算的時候將feature2變爲了與center2同樣的維度,等同於如下的計算:
feature3 = np.array([[2,3,5],[2,3,5]])
result3 = feature3 - center2
print("python的廣播機制:")
print(result3)
print(result3.shape)
結果:
原始數據維度:
(3,)
(3,)
維度相同的減法:
[1 1 2]
******************
擴充維度:
(1, 3)
(2, 3)
維度不同的減法:
[[1 1 2]
[0 0 1]]
(2, 3)
python的廣播機制:
[[1 1 2]
[0 0 1]]
(2, 3)