Numpy入門教程:練習作業03

背景

什麼是 NumPy 呢?

NumPy 這個詞來源於兩個單詞 – NumericalPython。其是一個功能強大的 Python 庫,可以幫助程序員輕鬆地進行數值計算,通常應用於以下場景:

  • 執行各種數學任務,如:數值積分、微分、內插、外推等。因此,當涉及到數學任務時,它形成了一種基於 Python 的 MATLAB 的快速替代。
  • 計算機中的圖像表示爲多維數字數組。NumPy 提供了一些優秀的庫函數來快速處理圖像。例如,鏡像圖像、按特定角度旋轉圖像等。
  • 在編寫機器學習算法時,需要對矩陣進行各種數值計算。如:矩陣乘法、求逆、換位、加法等。NumPy 數組用於存儲訓練數據和機器學習模型的參數。

練習作業

本次練習使用 鳶尾屬植物數據集.\iris.data,在這個數據集中,包括了三類不同的鳶尾屬植物:Iris Setosa,Iris Versicolour,Iris Virginica。每類收集了50個樣本,因此這個數據集一共包含了150個樣本。

  • sepallength:萼片長度
  • sepalwidth:萼片寬度
  • petallength:花瓣長度
  • petalwidth:花瓣寬度

以上四個特徵的單位都是釐米(cm)。

     sepallength  sepalwidth  petallength  petalwidth         species
0            5.1         3.5          1.4         0.2     Iris-setosa
1            4.9         3.0          1.4         0.2     Iris-setosa
2            4.7         3.2          1.3         0.2     Iris-setosa
3            4.6         3.1          1.5         0.2     Iris-setosa
4            5.0         3.6          1.4         0.2     Iris-setosa
..           ...         ...          ...         ...             ...
145          6.7         3.0          5.2         2.3  Iris-virginica
146          6.3         2.5          5.0         1.9  Iris-virginica
147          6.5         3.0          5.2         2.0  Iris-virginica
148          6.2         3.4          5.4         2.3  Iris-virginica
149          5.9         3.0          5.1         1.8  Iris-virginica

[150 rows x 5 columns]

36. 根據 sepallength 列對數據集進行排序。

【知識點:排序】

  • 如何按列對2D數組進行排序?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
sepalLength = iris_data[:, 0]
index = np.argsort(sepalLength)
print(iris_data[index][0:10])
# [['4.3' '3.0' '1.1' '0.1' 'Iris-setosa']
#  ['4.4' '3.2' '1.3' '0.2' 'Iris-setosa']
#  ['4.4' '3.0' '1.3' '0.2' 'Iris-setosa']
#  ['4.4' '2.9' '1.4' '0.2' 'Iris-setosa']
#  ['4.5' '2.3' '1.3' '0.3' 'Iris-setosa']
#  ['4.6' '3.6' '1.0' '0.2' 'Iris-setosa']
#  ['4.6' '3.1' '1.5' '0.2' 'Iris-setosa']
#  ['4.6' '3.4' '1.4' '0.3' 'Iris-setosa']
#  ['4.6' '3.2' '1.4' '0.2' 'Iris-setosa']
#  ['4.7' '3.2' '1.3' '0.2' 'Iris-setosa']]

37. 在鳶尾屬植物數據集中找到最常見的花瓣長度值(第3列)。

【知識點:數組操作】

  • 如何在numpy數組中找出出現次數最多的值?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
petalLength = iris_data[:, 2]
vals, counts = np.unique(petalLength, return_counts=True)
print(vals[np.argmax(counts)])  # 1.5
print(np.amax(counts))  # 14

38. 在鳶尾花數據集的 petalwidth(第4列)中查找第一次出現的值大於1.0的位置。

【知識點:搜索】

  • 如何找到第一次出現大於給定值的位置?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
petalWidth = iris_data[:, 3]
index = np.where(petalWidth > 1.0)
print(index)
print(index[0][0])  # 50

39. 將數組a中大於30的值替換爲30,小於10的值替換爲10。

  • a = np.random.uniform(1, 50, 20)

【知識點:數學函數、搜索】

  • 如何將大於給定值的所有值替換爲給定的截止值?

【答案】

import numpy as np

np.set_printoptions(precision=2)
np.random.seed(100)
a = np.random.uniform(1, 50, 20)
print(a)
# [27.63 14.64 21.8  42.39  1.23  6.96 33.87 41.47  7.7  29.18 44.67 11.25
#  10.08  6.31 11.77 48.95 40.77  9.43 41.   14.43]

# 方法1
b = np.clip(a, a_min=10, a_max=30)
print(b)
# [27.63 14.64 21.8  30.   10.   10.   30.   30.   10.   29.18 30.   11.25
#  10.08 10.   11.77 30.   30.   10.   30.   14.43]

# 方法2
b = np.where(a < 10, 10, a)
b = np.where(b > 30, 30, b)
print(b)
# [27.63 14.64 21.8  30.   10.   10.   30.   30.   10.   29.18 30.   11.25
#  10.08 10.   11.77 30.   30.   10.   30.   14.43]

40. 獲取給定數組a中前5個最大值的位置。

  • a = np.random.uniform(1, 50, 20)

【知識點:搜索】

  • 如何從numpy數組中獲取最大的n個值的位置?

【答案】

import numpy as np

np.random.seed(100)
a = np.random.uniform(1, 50, 20)
print(a)
# [27.62684215 14.64009987 21.80136195 42.39403048  1.23122395  6.95688692
#  33.86670515 41.466785    7.69862289 29.17957314 44.67477576 11.25090398
#  10.08108276  6.31046763 11.76517714 48.95256545 40.77247431  9.42510962
#  40.99501269 14.42961361]

# 方法1
b = np.argsort(a)
print(b)
print(b[-5:])
# [18  7  3 10 15]

# 方法2
b = np.sort(a)
b = np.where(a >= b[-5])
print(b)
# (array([ 3,  7, 10, 15, 18], dtype=int64),)

# 方法3
b = np.argpartition(a, kth=-5)
print(b[-5:])
# [18  7  3 10 15]

41. 計算給定數組中每行的最大值。

  • a = np.random.randint(1, 10, [5, 3])

【知識點:統計相關】

  • 如何在二維numpy數組的每一行中找到最大值?

【答案】

import numpy as np

np.random.seed(100)
a = np.random.randint(1, 10, [5, 3])
print(a)
# [[9 9 4]
#  [8 8 1]
#  [5 3 6]
#  [3 3 3]
#  [2 1 9]]

b = np.amax(a, axis=1)
print(b)
# [9 8 6 3 9]

42. 在給定的numpy數組中找到重複的條目(第二次出現以後),並將它們標記爲True。第一次出現應爲False。

  • a = np.random.randint(0, 5, 10)

【知識點:數組操作】

  • 如何在numpy數組中找到重複值?

【答案】

import numpy as np

np.random.seed(100)
a = np.random.randint(0, 5, 10)
print(a)
# [0 0 3 0 2 4 2 2 2 2]
b = np.full(10, True)
vals, counts = np.unique(a, return_index=True)
b[counts] = False
print(b)
# [False  True False  True False False  True  True  True  True]

43. 刪除一維numpy數組中所有NaN值。

  • a = np.array([1, 2, 3, np.nan, 5, 6, 7, np.nan])

【知識點:邏輯函數、搜索】

  • 如何刪除numpy數組中的缺失值?

【答案】

import numpy as np

a = np.array([1, 2, 3, np.nan, 5, 6, 7, np.nan])
b = np.isnan(a)
c = np.where(np.logical_not(b))
print(a[c])
# [1. 2. 3. 5. 6. 7.]

44. 計算兩個數組a和數組b之間的歐氏距離。

  • a = np.array([1, 2, 3, 4, 5])
  • b = np.array([4, 5, 6, 7, 8])

【知識點:數學函數、線性代數】

  • 如何計算兩個數組之間的歐式距離?

【答案】

import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([4, 5, 6, 7, 8])

# 方法1
d = np.sqrt(np.sum((a - b) ** 2))
print(d)  # 6.708203932499369

# 方法2
d = np.linalg.norm(a - b)
print(d)  # 6.708203932499369

45. 找到一個一維數字數組a中的所有峯值。峯頂是兩邊被較小數值包圍的點。

  • a = np.array([1, 3, 7, 1, 2, 6, 0, 1])

【知識點:數學函數、搜索】

  • 如何在一維數組中找到所有的局部極大值(或峯值)?

【答案】

import numpy as np

a = np.array([1, 3, 7, 1, 2, 6, 0, 1])
b1 = np.diff(a)
b2 = np.sign(b1)
b3 = np.diff(b2)

print(b1)  # [ 2  4 -6  1  4 -6  1]
print(b2)  # [ 1  1 -1  1  1 -1  1]
print(b3)  # [ 0 -2  2  0 -2  2]
index = np.where(np.equal(b3, -2))[0] + 1
print(index) # [2 5]

46. 將numpy的datetime64對象轉換爲datetime的datetime對象。

  • dt64 = np.datetime64('2020-02-25 22:10:10')

【知識點:時間日期和時間增量】

  • 如何將numpy的datetime64對象轉換爲datetime的datetime對象?

【答案】

import numpy as np
import datetime

dt64 = np.datetime64('2020-02-25 22:10:10')
dt = dt64.astype(datetime.datetime)
print(dt, type(dt))
# 2020-02-25 22:10:10 <class 'datetime.datetime'>

47. 給定一系列不連續的日期序列。填充缺失的日期,使其成爲連續的日期序列。

  • dates = np.arange('2020-02-01', '2020-02-10', 2, np.datetime64)

【知識點:時間日期和時間增量、數學函數】

  • 如何填寫不規則系列的numpy日期中的缺失日期?

【答案】

import numpy as np

dates = np.arange('2020-02-01', '2020-02-10', 2, np.datetime64)
print(dates)
# ['2020-02-01' '2020-02-03' '2020-02-05' '2020-02-07' '2020-02-09']

out = []
for date, d in zip(dates, np.diff(dates)):
    out.extend(np.arange(date, date + d))
fillin = np.array(out)
output = np.hstack([fillin, dates[-1]])
print(output)
# ['2020-02-01' '2020-02-02' '2020-02-03' '2020-02-04' '2020-02-05'
#  '2020-02-06' '2020-02-07' '2020-02-08' '2020-02-09']

48. 對於給定的一維數組,計算窗口大小爲3的移動平均值。

  • z = np.random.randint(10, size=10)

【知識點:數學函數】

  • 如何計算numpy數組的移動平均值?

【答案】

import numpy as np

np.random.seed(100)
z = np.random.randint(10, size=10)
print(z)
# [8 8 3 7 7 0 4 2 5 2]

def MovingAverage(arr, n=3):
    a = np.cumsum(arr)
    a[n:] = a[n:] - a[:-n]
    return a[n - 1:] / n


r = MovingAverage(z, 3)
print(np.around(r, 2))
# [6.33 6.   5.67 4.67 3.67 2.   3.67 3.  ]

49. 創建長度爲10的numpy數組,從5開始,在連續的數字之間的步長爲3。

【知識點:數組的創建與屬性】

  • 如何在給定起始點、長度和步驟的情況下創建一個numpy數組序列?

【答案】

import numpy as np

start = 5
step = 3
length = 10
a = np.arange(start, start + step * length, step)
print(a)  # [ 5  8 11 14 17 20 23 26 29 32]

50. 將本地圖像導入並將其轉換爲numpy數組。

【知識點:數組的創建與屬性】

  • 如何將圖像轉換爲numpy數組?

【答案】

import numpy as np
from PIL import Image

img1 = Image.open('test.jpg')
a = np.array(img1)

print(a.shape, a.dtype)
# (1200, 750, 3) uint8

當前活動


我是 終身學習者“老馬”,一個長期踐行“結伴式學習”理念的 中年大叔

我崇尚分享,渴望成長,於2010年創立了“LSGO軟件技術團隊”,並加入了國內著名的開源組織“Datawhale”,也是“Dre@mtech”、“智能機器人研究中心”和“大數據與哲學社會科學實驗室”的一員。

願我們一起學習,一起進步,相互陪伴,共同成長。

後臺回覆「搜搜搜」,隨機獲取電子資源!
歡迎關注,請掃描二維碼:

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