Python——Numpy模塊

一、Numpy操作

1. 基本操作
import numpy as np

a = np.array([[1, 2, 3], [3, 4, 5]])

# 數組元素的總數,這等於 shape 的元素的乘積
print(a.size)

# 數組的軸(維度)的個數
print(a.ndim)

# 數組的維度
print(a.shape)

# 一個描述數組中元素類型的對象
print(a.dtype)

# 數組類型
print(type(a))

# 零矩陣
zero = np.zeros((3, 4))
print(zero)
# 1矩陣
one = np.ones((3, 4))
print(one)

# 創建滿足高斯分佈的隨機矩陣
rand = np.random.randn(2, 3)
print(rand)

# 創建隨機矩陣
empt = np.empty((2, 3))
print(empt)

# 創建均勻分佈的矩陣,創建0到1之間的數,形狀是(3, 4)  	
p = np.random.uniform(0, 1, (3, 4))
print(p)

# 創建數組,並且變換其形狀,變換形狀時兩個維度的乘積要等與原來的值
b = np.arange(15).reshape(3, 5)
print(type(b))

# 創建數組,表示將0到6的數分爲9份
linespac = np.linspace(0, 6, 9)
print(linespac)

# a > 3 或者 a < 4 這個在過濾值的時候非常有用
b = np.arange(15).reshape(3, 5)
print(b)  
""" 
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
"""
print(b[b > 3]) # 取出大於三的元素
print(np.where(b>3)) # b > 3 的數的索引
""" 
[ 4  5  6  7  8  9 10 11 12 13 14]

"""

# 點乘
b * b

# 叉乘
a @ b
# 或者
a.dot(b)

二、聚合操作

a = np.arange(0, 12).reshape(3, 4)
print(a)

# 求所有數的和
print(a.sum())

# 按列求和
print(a.sum(axis=0))

# 按行求和
print(a.sum(axis=1))

img = np.random.randn(2, 64, 64, 3)
print(img)

# 對於圖片來說,N H W C  (0, 1, 2, 3)
print(img.mean(axis=0)) # 在樣本維度上做均值,也即每個樣本加起來做均值
print(img.mean(axis=3)) # 在通道上做均值,每個通道的對應像素點加起來求均值
print(img.max()) # 求最大值

# argmax()函數求最大值所在位置	
print(img.argmax(axis=3)) # 求通道上最大值的位置
print(a.cumsum(axis=1))# 按行加,後一個元素是前面元素的和
"""
[[ 0  1  2  3]           
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 0  1  3  6]   # 0  0+1  0+1+2  0+1+2+3
 [ 4  9 15 22]   # 4  4+5  4+5+6  4+5+6+7
 [ 8 17 27 38]]  # 8  8+9  8+9+10  8+9+10+11
"""

三、切片索引

"""
索引和切片
"""
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a[1][1])
print(a[0][2])
print(a[1, 2])

"""切片"""
print(a[0:2, 0:2])
print(a[0:2, 1])
print(a[0:2][:1])
print(a[1, :2])
b = np.arange(24).reshape(2, 3, 4)
print(b)
print(b[:1, 0:2])
print(b[:, 2, :2])
print(b[:1][0:1][0:2])
print(b[:, 0:1, 0:2])
print(b[1:, 1, 2:4])
b[0, 2] = 0
print(b)
print(b[:, 2:5, 3][:1])

"""
布爾索引
"""
x = np.array([True, False, True, True, False, False])
y = np.array([1, 2, 3, 4, 5 ,6])
print(y[x])
print(y[x == False])

y = np.arange(5)
print(y)
print(y[y > 2])


"""花式索引"""
x = np.array([0, 2, 3])
y = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 54, 6]])
print(y[x])

"""加維度"""
a = np.arange(1, 12)
print(a)
print(a.shape)

"""方法一: 在哪裏加一個維度,就在什麼位置添加None"""
b = a[:, None]
c = a[None, :]
print(c)
print(b)

"""方法二:用np.newaxis"""
print(a[:, np.newaxis])
print(a[np.newaxis, :])

"""刪除維度: 刪除維度的時候需要注意,必須是一維纔可以"""
print(b[:, 0]) # 在一維的地方將維度設爲0表示刪除了這個維度
print(c[0, :])

"""也可以刪除一維的維度,並將其展平"""
print(b.flatten())
print(c.flatten())

"""兩個列表合併"""
a = np.array([[1, 2, 3], [3, 4, 5]])
b = np.array([[5, 6, 7], [7, 8, 9]])
# print(a)
# print(b)

"""方法一:stack()"""
c0 = np.stack((a, b), axis=0)
c1 = np.stack((a, b), axis=1)
c2 = np.stack((a, b), axis=2)
print(c0)
print(c1)
print(c2)

"""方法二: concatenate()"""
c0 = np.concatenate((a, b), axis=0)
c1 = np.concatenate((a, b), axis=1)
print(c0)
print(c1)

"""翻轉"""
import numpy as np
a = np.arange(10)  # [0 1 2 3 4 5 6 7 8 9]
print(a[::-1])  # [9 8 7 6 5 4 3 2 1 0]

rgb = np.random.randn(2, 3, 2, 2)
print(rgb)
bgr = rgb[:, ::-1, :, :] # ::-1 表示將通道維度的三個通道進行取反RGB --> BGR
print(bgr)

練習:利用索引和切片對圖片進行切割

  1. 將一張圖片利用切片索引分成四塊
    在這裏插入圖片描述
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

img = Image.open("bird.jpg")
# img.show()
img_data = np.array(img)
img_data = img_data.reshape((2, 338//2, 2, 500//2, 3))
img_data = img_data.transpose((0, 2, 1, 3, 4))
img_data = img_data.reshape((-1, 169, 250, 3))
imgs = np.split(img_data, 4, axis=0)
img_list = []
for img in imgs:
    print(img.shape)
    # img_finall = Image.fromarray(img[0])
    img_list.append(img[0])

plt.subplot(2, 2, 1)
plt.imshow(img_list[0])
plt.tight_layout(0.1)
plt.axis("off")
plt.subplot(2, 2, 2)
plt.imshow(img_list[1])
# plt.tight_layout(0.1)
plt.axis("off")

plt.subplot(2, 2, 3)
plt.imshow(img_list[2])
# plt.tight_layout(0.1)
plt.axis("off")

plt.subplot(2, 2, 4)
plt.imshow(img_list[3])
plt.axis("off")
plt.tight_layout(0.1)
plt.show()
  1. 將切分成的四張圖片恢復成一張圖片
    在這裏插入圖片描述
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

img = Image.open("bird.jpg")
# img.show()

"""拆分圖片"""
img_data = np.array(img)
img_data = img_data.reshape((2, 338//2, 2, 500//2, 3))
img_data = img_data.transpose((0, 2, 1, 3, 4))
img_data = img_data.reshape((-1, 169, 250, 3))
imgs = np.split(img_data, 4, axis=0)
img_list = []
for img in imgs:
    print(img.shape)
    # img_finall = Image.fromarray(img[0])
    img_list.append(img[0])


"""合併圖像"""
# img_data = np.stack((img_list[0], img_list[1], img_list[2], img_list[3]))
img_data = np.concatenate((img_list[0], img_list[1], img_list[2], img_list[3]), axis=0)
img_data = img_data.reshape((2, 2, 169, 250, 3))
print(img_data.shape)
img_data = img_data.transpose(0, 2, 1, 3, 4)

img = img_data.reshape(338, 500, 3)
print(img.shape)
plt.imshow(img)
plt.axis('off')
plt.show()

四、廣播

  1. 廣播允許通用功能以有意義的方式處理不具有完全相同形狀的輸入。
  2. 廣播的第一個規則是,如果所有輸入數組不具有相同數量的維度,則將“1”重複地預先添加到較小數組的形狀,直到所有數組具有相同數量的維度。
  3. 廣播的第二個規則確保沿特定維度的大小爲1的數組表現爲具有沿該維度具有最大形狀的數組的大小。
  4. 假定數組元素的值沿着“廣播”數組的那個維度是相同的。應用廣播規則後,所有數組的大小必須匹配
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([3, 4])
c = np.array([[3], [4]])

# 行廣播
print(a + b)

# 列廣播
print(a + c)

# tile()函數,相當於複製的作用
a = np.array([5])
# 將a矩陣分別在行和列上覆制兩份
b = np.tile(a, [2, 2])
print(a) # [5]
print(b) 
""" 
[[5 5]
 [5 5]]
"""

c = np.array([5, 6]) 
d = np.tile(c, [3]) 
e = np.tile(c, [3, 1])

print(c) # [5 6]
print(d) # [5 6 5 6 5 6]
print(e)
"""
[[5 6]
 [5 6]
 [5 6]]
"""

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章