DataWhale-Numpy学习(下)05-大作业

Numpy学习(下)05


学习资料来自于http://datawhale.club/t/topic/187


本次练习使用 鸢尾属植物数据集.\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]

1. 导入鸢尾属植物数据集,保持文本不变。

【知识点:输入和输出】

  • 如何导入存在数字和文本的数据集?
# Solution
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

 2. 求出鸢尾属植物萼片长度的平均值、中位数和标准差(第1列,sepallength)

【知识点:统计相关】

  • 如何计算numpy数组的均值,中位数,标准差?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])

# Solution
mu, med, sd = np.mean(sepallength), np.median(sepallength), np.std(sepallength)
print(mu, med, sd)
#5.843333333333334 5.8 0.8253012917851409

 3. 创建一种标准化形式的鸢尾属植物萼片长度,其值正好介于0和1之间,这样最小值为0,最大值为1(第1列,sepallength)。

【知识点:统计相关】

  • 如何标准化数组?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])

# Solution
Smax, Smin = sepallength.max(), sepallength.min()
S = (sepallength - Smin)/(Smax - Smin)
# or 
S = (sepallength - Smin)/sepallength.ptp()  # Thanks, David Ojeda!
print(S)

[0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556
 0.08333333 0.19444444 0.02777778 0.16666667 0.30555556 0.13888889
 0.13888889 0.         0.41666667 0.38888889 0.30555556 0.22222222
 0.38888889 0.22222222 0.30555556 0.22222222 0.08333333 0.22222222
 0.13888889 0.19444444 0.19444444 0.25       0.25       0.11111111
 0.13888889 0.30555556 0.25       0.33333333 0.16666667 0.19444444
 0.33333333 0.16666667 0.02777778 0.22222222 0.19444444 0.05555556
 0.02777778 0.19444444 0.22222222 0.13888889 0.22222222 0.08333333
 0.27777778 0.19444444 0.75       0.58333333 0.72222222 0.33333333
 0.61111111 0.38888889 0.55555556 0.16666667 0.63888889 0.25
 0.19444444 0.44444444 0.47222222 0.5        0.36111111 0.66666667
 0.36111111 0.41666667 0.52777778 0.36111111 0.44444444 0.5
 0.55555556 0.5        0.58333333 0.63888889 0.69444444 0.66666667
 0.47222222 0.38888889 0.33333333 0.33333333 0.41666667 0.47222222
 0.30555556 0.47222222 0.66666667 0.55555556 0.36111111 0.33333333
 0.33333333 0.5        0.41666667 0.19444444 0.36111111 0.38888889
 0.38888889 0.52777778 0.22222222 0.38888889 0.55555556 0.41666667
 0.77777778 0.55555556 0.61111111 0.91666667 0.16666667 0.83333333
 0.66666667 0.80555556 0.61111111 0.58333333 0.69444444 0.38888889
 0.41666667 0.58333333 0.61111111 0.94444444 0.94444444 0.47222222
 0.72222222 0.36111111 0.94444444 0.55555556 0.66666667 0.80555556
 0.52777778 0.5        0.58333333 0.80555556 0.86111111 1.
 0.58333333 0.55555556 0.5        0.94444444 0.55555556 0.58333333
 0.47222222 0.72222222 0.66666667 0.72222222 0.41666667 0.69444444
 0.66666667 0.66666667 0.55555556 0.61111111 0.52777778 0.44444444]

 4. 找到鸢尾属植物萼片长度的第5和第95百分位数(第1列,sepallength)。

【知识点:统计相关】

  • 如何找到numpy数组的百分位数?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])

# Solution
np.percentile(sepallength, q=[5, 95])
#array([4.6  , 7.255])

5. 把iris_data数据集中的20个随机位置修改为np.nan值。

【知识点:随机抽样】

  • 如何在数组中的随机位置修改值?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')

# Method 1
i, j = np.where(iris_2d)

# i, j contain the row numbers and column numbers of 600 elements of iris_x
np.random.seed(100)
iris_2d[np.random.choice((i), 20), np.random.choice((j), 20)] = np.nan

# Method 2
np.random.seed(100)
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

# Print first 10 rows
print(iris_2d[:10])

[[b'5.1' b'3.5' b'1.4' b'0.2' b'Iris-setosa']
 [b'4.9' b'3.0' b'1.4' b'0.2' b'Iris-setosa']
 [b'4.7' b'3.2' b'1.3' b'0.2' b'Iris-setosa']
 [b'4.6' b'3.1' b'1.5' b'0.2' b'Iris-setosa']
 [b'5.0' b'3.6' b'1.4' b'0.2' b'Iris-setosa']
 [b'5.4' b'3.9' b'1.7' b'0.4' b'Iris-setosa']
 [b'4.6' b'3.4' b'1.4' b'0.3' b'Iris-setosa']
 [b'5.0' b'3.4' b'1.5' b'0.2' b'Iris-setosa']
 [b'4.4' nan b'1.4' b'0.2' b'Iris-setosa']
 [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']]

6. 在iris_data的sepallength中查找缺失值的个数和位置(第1列)。

【知识点:逻辑函数、搜索】

  • 如何在numpy数组中找到缺失值的位置?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

# Solution
print("Number of missing values: \n", np.isnan(iris_2d[:, 0]).sum())
print("Position of missing values: \n", np.where(np.isnan(iris_2d[:, 0])))

#Number of missing values: 
# 5
#Position of missing values: 
# (array([ 38,  80, 106, 113, 121], dtype=int64),)

7. 筛选具有 sepallength(第1列)< 5.0 并且 petallength(第3列)> 1.5 的 iris_data行。

【知识点:搜索】

  • 如何根据两个或多个条件筛选numpy数组?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

# Solution
condition = (iris_2d[:, 2] > 1.5) & (iris_2d[:, 0] < 5.0)
iris_2d[condition]

#array([[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]])

8. 选择没有任何 nan 值的 iris_data行。

【知识点:逻辑函数、搜索】

  • 如何从numpy数组中删除包含缺失值的行?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

# Solution
# No direct numpy function for this.
# Method 1:
any_nan_in_row = np.array([~np.any(np.isnan(row)) for row in iris_2d])
iris_2d[any_nan_in_row][:5]

# Method 2: (By Rong)
iris_2d[np.sum(np.isnan(iris_2d), axis = 1) == 0][:5]
#  array([[ 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,  3.9,  1.7,  0.4]])

9. 计算 iris_data 中sepalLength(第1列)和petalLength(第3列)之间的相关系数。

【知识点:统计相关】

  • 如何计算numpy数组两列之间的相关系数?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

# Solution 1
np.corrcoef(iris[:, 0], iris[:, 2])[0, 1]

# Solution 2
from scipy.stats.stats import pearsonr  
corr, p_value = pearsonr(iris[:, 0], iris[:, 2])
print(corr)

#0.8717541573048713

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

【知识点:逻辑函数】

  • 如何查找给定数组是否具有空值?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

np.isnan(iris_2d).any()
# False

 11. 在numpy数组中将所有出现的nan替换为0。

【知识点:逻辑函数】

  • 如何在numpy数组中用0替换所有缺失值?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

# Solution
iris_2d[np.isnan(iris_2d)] = 0
iris_2d[:4]

#  array([[ 5.1,  3.5,  1.4,  0. ],
#         [ 4.9,  3. ,  1.4,  0.2],
#         [ 4.7,  3.2,  1.3,  0.2],
#         [ 4.6,  3.1,  1.5,  0.2]])

 12. 找出鸢尾属植物物种中的唯一值和唯一值出现的数量。

【知识点:数组操作】

  • 如何在numpy数组中查找唯一值的计数?
# Import iris keeping the text column intact
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

# Solution
# Extract the species column as an array
species = np.array([row.tolist()[4] for row in iris])

# Get the unique values and the counts
np.unique(species, return_counts=True)
# > (array([b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'],
# >        dtype='|S15'), array([50, 50, 50]))

 13. 将 iris_data 的花瓣长度(第3列)以形成分类变量的形式显示。定义:Less than 3 --> ‘small’;3-5 --> ‘medium’;’>=5 --> ‘large’。

【知识点:统计相关】

  • 如何将数字转换为分类(文本)数组?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

# Bin petallength 
petal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10])

# Map it to respective category
label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}
petal_length_cat = [label_map[x] for x in petal_length_bin]

# View
petal_length_cat[:4]
<# > ['small', 'small', 'small', 'small']

 14. 在 iris_data 中创建一个新列,其中 volume 是 (pi x petallength x sepallength ^ 2)/ 3

【知识点:数组操作】

  • 如何从numpy数组的现有列创建新列?
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')

# Solution
# Compute volume
sepallength = iris_2d[:, 0].astype('float')
petallength = iris_2d[:, 2].astype('float')
volume = (np.pi * petallength * (sepallength**2))/3

# Introduce new dimension to match iris_2d's
volume = volume[:, np.newaxis]

# Add the new column
out = np.hstack([iris_2d, volume])

# View
out[:4]
# > array([[b'5.1', b'3.5', b'1.4', b'0.2', b'Iris-setosa', 38.13265162927291],
# >        [b'4.9', b'3.0', b'1.4', b'0.2', b'Iris-setosa', 35.200498485922445],
# >        [b'4.7', b'3.2', b'1.3', b'0.2', b'Iris-setosa', 30.0723720777127],
# >        [b'4.6', b'3.1', b'1.5', b'0.2', b'Iris-setosa', 33.238050274980004]], dtype=object)

 15. 随机抽鸢尾属植物的种类,使得Iris-setosa的数量是Iris-versicolor和Iris-virginica数量的两倍。

【知识点:随机抽样】

  • 如何在numpy中进行概率抽样?
# Import iris keeping the text column intact
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

# Solution
# Get the species column
species = iris[:, 4]

# Approach 1: Generate Probablistically
np.random.seed(100)
a = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
species_out = np.random.choice(a, 150, p=[0.5, 0.25, 0.25])

# Approach 2: Probablistic Sampling (preferred)
np.random.seed(100)
probs = np.r_[np.linspace(0, 0.500, num=50), np.linspace(0.501, .750, num=50), np.linspace(.751, 1.0, num=50)]
index = np.searchsorted(probs, np.random.random(150))
species_out = species[index]
print(np.unique(species_out, return_counts=True))

# > (array([b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'], dtype=object), array([77, 37, 36]))

# 方法2是首选方法,因为它创建了一个索引变量,该变量可用于取样2维表格数据

 16. 根据 sepallength 列对数据集进行排序。

【知识点:排序】

  • 如何按列对2D数组进行排序?
# Sort by column position 0: SepalLength
print(iris[iris[:,0].argsort()][:20])
#  [[b'4.3' b'3.0' b'1.1' b'0.1' b'Iris-setosa']
#   [b'4.4' b'3.2' b'1.3' b'0.2' b'Iris-setosa']
#   [b'4.4' b'3.0' b'1.3' b'0.2' b'Iris-setosa']
#   [b'4.4' b'2.9' b'1.4' b'0.2' b'Iris-setosa']
#   [b'4.5' b'2.3' b'1.3' b'0.3' b'Iris-setosa']
#   [b'4.6' b'3.6' b'1.0' b'0.2' b'Iris-setosa']
#   [b'4.6' b'3.1' b'1.5' b'0.2' b'Iris-setosa']
#   [b'4.6' b'3.4' b'1.4' b'0.3' b'Iris-setosa']
#   [b'4.6' b'3.2' b'1.4' b'0.2' b'Iris-setosa']
#   [b'4.7' b'3.2' b'1.3' b'0.2' b'Iris-setosa']
#   [b'4.7' b'3.2' b'1.6' b'0.2' b'Iris-setosa']
#   [b'4.8' b'3.0' b'1.4' b'0.1' b'Iris-setosa']
#   [b'4.8' b'3.0' b'1.4' b'0.3' b'Iris-setosa']
#   [b'4.8' b'3.4' b'1.9' b'0.2' b'Iris-setosa']
#   [b'4.8' b'3.4' b'1.6' b'0.2' b'Iris-setosa']
#   [b'4.8' b'3.1' b'1.6' b'0.2' b'Iris-setosa']
#   [b'4.9' b'2.4' b'3.3' b'1.0' b'Iris-versicolor']
#   [b'4.9' b'2.5' b'4.5' b'1.7' b'Iris-virginica']
#   [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']
#   [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']]

 17. 在鸢尾属植物数据集中找到最常见的花瓣长度值(第3列)。

【知识点:数组操作】

  • 如何在numpy数组中找出出现次数最多的值?
# Input:
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

# Solution:
vals, counts = np.unique(iris[:, 2], return_counts=True)
print(vals[np.argmax(counts)])
# > b'1.5'

 18. 在鸢尾花数据集的 petalwidth(第4列)中查找第一次出现的值大于1.0的位置。

【知识点:搜索】

  • 如何找到第一次出现大于给定值的位置?
# Input:
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

# Solution: (edit: changed argmax to argwhere. Thanks Rong!)
np.argwhere(iris[:, 3].astype(float) > 1.0)[0]
# > 50

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值