Numpy入門教程:練習作業02

背景

什麼是 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]

21. 導入鳶尾屬植物數據集,保持文本不變。

【知識點:輸入和輸出】

  • 如何導入存在數字和文本的數據集?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris-setosa']
#  ['4.9' '3.0' '1.4' '0.2' 'Iris-setosa']
#  ['4.7' '3.2' '1.3' '0.2' 'Iris-setosa']
#  ['4.6' '3.1' '1.5' '0.2' 'Iris-setosa']
#  ['5.0' '3.6' '1.4' '0.2' 'Iris-setosa']
#  ['5.4' '3.9' '1.7' '0.4' 'Iris-setosa']
#  ['4.6' '3.4' '1.4' '0.3' 'Iris-setosa']
#  ['5.0' '3.4' '1.5' '0.2' 'Iris-setosa']
#  ['4.4' '2.9' '1.4' '0.2' 'Iris-setosa']
#  ['4.9' '3.1' '1.5' '0.1' 'Iris-setosa']]

22. 求出鳶尾屬植物萼片長度的平均值、中位數和標準差(第1列,sepallength)

【知識點:統計相關】

  • 如何計算numpy數組的均值,中位數,標準差?

【答案】

import numpy as np

outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])
print(sepalLength[0:10])
# [5.1 4.9 4.7 4.6 5.  5.4 4.6 5.  4.4 4.9]

print(np.mean(sepalLength))
# 5.843333333333334

print(np.median(sepalLength))
# 5.8

print(np.std(sepalLength))
# 0.8253012917851409

23. 創建一種標準化形式的鳶尾屬植物萼片長度,其值正好介於0和1之間,這樣最小值爲0,最大值爲1(第1列,sepallength)。

【知識點:統計相關】

  • 如何標準化數組?

【答案】

import numpy as np

outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])

# 方法1
aMax = np.amax(sepalLength)
aMin = np.amin(sepalLength)
x = (sepalLength - aMin) / (aMax - aMin)
print(x[0:10])
# [0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556
#  0.08333333 0.19444444 0.02777778 0.16666667]

# 方法2
x = (sepalLength - aMin) / np.ptp(sepalLength)
print(x[0:10])
# [0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556
#  0.08333333 0.19444444 0.02777778 0.16666667]

24. 找到鳶尾屬植物萼片長度的第5和第95百分位數(第1列,sepallength)。

【知識點:統計相關】

  • 如何找到numpy數組的百分位數?

【答案】

import numpy as np

outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])
x = np.percentile(sepalLength, [5, 95])
print(x)  # [4.6   7.255]

25. 把iris_data數據集中的20個隨機位置修改爲np.nan值。

【知識點:隨機抽樣】

  • 如何在數組中的隨機位置修改值?

【答案】

import numpy as np

outfile = r'.\iris.data'

# 方法1
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
i, j = iris_data.shape
np.random.seed(20200621)
iris_data[np.random.randint(i, size=20), np.random.randint(j, size=20)] = np.nan
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris-setosa']
#  ['4.9' '3.0' '1.4' '0.2' 'Iris-setosa']
#  ['4.7' '3.2' '1.3' '0.2' 'Iris-setosa']
#  ['4.6' '3.1' '1.5' '0.2' 'Iris-setosa']
#  ['5.0' '3.6' '1.4' '0.2' 'Iris-setosa']
#  ['5.4' nan '1.7' '0.4' 'Iris-setosa']
#  ['4.6' '3.4' '1.4' '0.3' 'Iris-setosa']
#  ['5.0' '3.4' '1.5' '0.2' 'Iris-setosa']
#  ['4.4' '2.9' '1.4' '0.2' nan]
#  ['4.9' '3.1' '1.5' '0.1' 'Iris-setosa']]

# 方法2
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
i, j = iris_data.shape
np.random.seed(20200620)
iris_data[np.random.choice(i, size=20), np.random.choice(j, size=20)] = np.nan
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris-setosa']
#  ['4.9' '3.0' '1.4' '0.2' 'Iris-setosa']
#  ['4.7' '3.2' '1.3' '0.2' 'Iris-setosa']
#  ['4.6' '3.1' '1.5' '0.2' 'Iris-setosa']
#  [nan '3.6' '1.4' '0.2' 'Iris-setosa']
#  ['5.4' '3.9' '1.7' '0.4' 'Iris-setosa']
#  ['4.6' '3.4' '1.4' '0.3' 'Iris-setosa']
#  ['5.0' '3.4' '1.5' '0.2' 'Iris-setosa']
#  ['4.4' '2.9' '1.4' '0.2' 'Iris-setosa']
#  ['4.9' '3.1' '1.5' nan 'Iris-setosa']]

26. 在iris_data的sepallength中查找缺失值的個數和位置(第1列)。

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

  • 如何在numpy數組中找到缺失值的位置?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
i, j = iris_data.shape
np.random.seed(20200621)
iris_data[np.random.randint(i, size=20), np.random.randint(j, size=20)] = np.nan
sepallength = iris_data[:, 0]
x = np.isnan(sepallength)
print(sum(x))  # 6
print(np.where(x))
# (array([ 26,  44,  55,  63,  90, 115], dtype=int64),)

27. 篩選具有 sepallength(第1列)< 5.0 並且 petallength(第3列)> 1.5 的 iris_data行。

【知識點:搜索】

  • 如何根據兩個或多個條件篩選numpy數組?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
sepallength = iris_data[:, 0]
petallength = iris_data[:, 2]
index = np.where(np.logical_and(petallength > 1.5, sepallength < 5.0))

print(iris_data[index])
# [[4.8 3.4 1.6 0.2]
#  [4.8 3.4 1.9 0.2]
#  [4.7 3.2 1.6 0.2]
#  [4.8 3.1 1.6 0.2]
#  [4.9 2.4 3.3 1. ]
#  [4.9 2.5 4.5 1.7]]

28. 選擇沒有任何 nan 值的 iris_data行。

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

  • 如何從numpy數組中刪除包含缺失值的行?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
i, j = iris_data.shape
np.random.seed(20200621)
iris_data[np.random.randint(i, size=20), np.random.randint(j, size=20)] = np.nan
x = iris_data[np.sum(np.isnan(iris_data), axis=1) == 0]
print(x[0:10])
# [[5.1 3.5 1.4 0.2]
#  [4.9 3.  1.4 0.2]
#  [4.7 3.2 1.3 0.2]
#  [4.6 3.1 1.5 0.2]
#  [5.  3.6 1.4 0.2]
#  [4.6 3.4 1.4 0.3]
#  [5.  3.4 1.5 0.2]
#  [4.9 3.1 1.5 0.1]
#  [5.4 3.7 1.5 0.2]
#  [4.8 3.4 1.6 0.2]]

29. 計算 iris_data 中sepalLength(第1列)和petalLength(第3列)之間的相關係數。

【知識點:統計相關】

  • 如何計算numpy數組兩列之間的相關係數?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
sepalLength = iris_data[:, 0]
petalLength = iris_data[:, 2]

# 方法1
m1 = np.mean(sepalLength)
m2 = np.mean(petalLength)
cov = np.dot(sepalLength - m1, petalLength - m2)
std1 = np.sqrt(np.dot(sepalLength - m1, sepalLength - m1))
std2 = np.sqrt(np.dot(petalLength - m2, petalLength - m2))
print(cov / (std1 * std2))  # 0.8717541573048712

# 方法2
x = np.mean((sepalLength - m1) * (petalLength - m2))
y = np.std(sepalLength) * np.std(petalLength)
print(x / y)  # 0.8717541573048712

# 方法3
x = np.cov(sepalLength, petalLength, ddof=False)
y = np.std(sepalLength) * np.std(petalLength)
print(x[0, 1] / y)  # 0.8717541573048716

# 方法4
x = np.corrcoef(sepalLength, petalLength)
print(x)
# [[1.         0.87175416]
#  [0.87175416 1.        ]]

30. 找出iris_data是否有任何缺失值。

【知識點:邏輯函數】

  • 如何查找給定數組是否具有空值?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
x = np.isnan(iris_data)
print(np.any(x))  # False

31. 在numpy數組中將所有出現的nan替換爲0。

【知識點:邏輯函數】

  • 如何在numpy數組中用0替換所有缺失值?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
i, j = iris_data.shape
np.random.seed(20200621)
iris_data[np.random.randint(i, size=20), np.random.randint(j, size=20)] = np.nan
iris_data[np.isnan(iris_data)] = 0
print(iris_data[0:10])
# [[5.1 3.5 1.4 0.2]
#  [4.9 3.  1.4 0.2]
#  [4.7 3.2 1.3 0.2]
#  [4.6 3.1 1.5 0.2]
#  [5.  3.6 1.4 0.2]
#  [5.4 0.  1.7 0.4]
#  [4.6 3.4 1.4 0.3]
#  [5.  3.4 1.5 0.2]
#  [4.4 2.9 0.  0.2]
#  [4.9 3.1 1.5 0.1]]

32. 找出鳶尾屬植物物種中的唯一值和唯一值出現的數量。

【知識點:數組操作】

  • 如何在numpy數組中查找唯一值的計數?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1, usecols=[4])
x = np.unique(iris_data, return_counts=True)

print(x)
# (array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object), array([50, 50, 50], dtype=int64))

33. 將 iris_data 的花瓣長度(第3列)以形成分類變量的形式顯示。定義:Less than 3 --> ‘small’;3-5 --> ‘medium’;’>=5 --> ‘large’。

【知識點:統計相關】

  • 如何將數字轉換爲分類(文本)數組?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0, 1, 2, 3])
petal_length_bin = np.digitize(iris_data[:, 2], [0, 3, 5, 10])
label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}
petal_length_cat = [label_map[x] for x in petal_length_bin]
print(petal_length_cat[0:10])
# ['small', 'small', 'small', 'small', 'small', 'small', 'small', 'small', 'small', 'small']

34. 在 iris_data 中創建一個新列,其中 volume 是 (pi x petallength x sepallength ^ 2)/ 3

【知識點:數組操作】

  • 如何從numpy數組的現有列創建新列?

【答案】

import numpy as np

outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
sepalLength = iris_data[:, 0].astype(float)
petalLength = iris_data[:, 2].astype(float)
volume = (np.pi * petalLength * sepalLength ** 2) / 3
volume = volume[:, np.newaxis]
iris_data = np.concatenate([iris_data, volume], axis=1)
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris-setosa' 38.13265162927291]
#  ['4.9' '3.0' '1.4' '0.2' 'Iris-setosa' 35.200498485922445]
#  ['4.7' '3.2' '1.3' '0.2' 'Iris-setosa' 30.0723720777127]
#  ['4.6' '3.1' '1.5' '0.2' 'Iris-setosa' 33.238050274980004]
#  ['5.0' '3.6' '1.4' '0.2' 'Iris-setosa' 36.65191429188092]
#  ['5.4' '3.9' '1.7' '0.4' 'Iris-setosa' 51.911677007917746]
#  ['4.6' '3.4' '1.4' '0.3' 'Iris-setosa' 31.022180256648003]
#  ['5.0' '3.4' '1.5' '0.2' 'Iris-setosa' 39.269908169872416]
#  ['4.4' '2.9' '1.4' '0.2' 'Iris-setosa' 28.38324242763259]
#  ['4.9' '3.1' '1.5' '0.1' 'Iris-setosa' 37.714819806345474]]

35. 隨機抽鳶尾屬植物的種類,使得Iris-setosa的數量是Iris-versicolor和Iris-virginica數量的兩倍。

【知識點:隨機抽樣】

  • 如何在numpy中進行概率抽樣?

【答案】

import numpy as np

species = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
species_out = np.random.choice(species, 10000, p=[0.5, 0.25, 0.25])
print(np.unique(species_out, return_counts=True))
# (array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype='<U15'), array([4927, 2477, 2596], dtype=int64))

當前活動


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

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

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

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

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