python 机器学习---Numpy学习 - array 本身支持的大量操作和函数

📅 2026-11-30 👤 拼多多助力营销技巧 📂 pdd助力 👁️ 115 次阅读

机器学习必修---Numpy学习

机器学习必修---Numpy学习开始了一、Numpy介绍二、Numpy的核心对象arrayarray 本身的属性:创建 array 的方法:array 本身支持的大量操作和函数

三、Numpy对数组按索引查询四、Numpy常用random随机函数五、Numpy的数学统计函数Numpy有哪些数学统计函数Numpy的 **axis** 参数的用途实例:机器学习将数据进行标准化

六、Numpy怎样给数组增加一个维度方法1:np.newaxis关键字方法2:np.expand_dims方法方法3:np.reshape方法

七、Numpy的数组合并操作

机器学习必修—Numpy学习开始了

一、Numpy介绍

Numpy ( Numerical Python 的缩写 ) :

一个开源的Python科学计算库使用Numpy可以方便的使用数组、矩阵进行计算包含线性代数、傅里叶变换、随机数生成大量函数

**Numpy VS Python **的优点 :

代码更加简洁

Numpy 直接以数组、矩阵为粒度计算并且支持大量的数学函数,而Python需要用 for 循环从底层实现;

性能更高效

Numpy 的数组存储效率和输入输出计算性能,比 Python 使用 List 或者嵌套 List 好很多;( Numpy大部分用C实现 )

Numpy是Python各种数据库的基础库

SciPy、Scikit-Learn、Tensorflow、PanddlePaddle等

二、Numpy的核心对象array

array 本身的属性:

shape :返回一个元组,表示 array 的维度ndim :一个数字,表示 array 的维度的数目size :一个数字,表示 array 中所有数据元素的数目dtype :array 中元素的数据类型

import numpy as np

arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

arr2 = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],

[1, 8, 9, 4, 5, 7, 3, 2, 6, 1]]

arr1 = np.array(arr1)

>>>arr

>>>[0 1 2 3 4 5 6 7 8 9]

arr2 = np.array(arr2)

>>>arr2

>>>[[0 1 2 3 4 5 6 7 8 9]

[1 8 9 4 5 7 3 2 6 1]]

# shape 维度

>>>arr1.shape #一维向量

>>>(10,)

>>>arr2.shape #二维数组

>>>(2,10)

# ndim 维数

>>>arr1.ndim

>>>1

>>>arr2.ndim

>>>2

# size 元素数目

>>>arr1.size

>>>10

>>>arr2.size

>>>20

# dtype array对象内元素只能有以一种类型

>>>arr1.dtype

>>>int32

>>>arr2.dtype

>>>int32

创建 array 的方法:

从Python的列表 List 和嵌套列表创建 array使用预定函数 arrange、ones/ones_like、zeros/zeros_like、empty/empty_like、full/full_like、eye等函数创建生成随机数的 np.random 模块构建

# 使用arange创建数字序列/和range的参数一致,只能创建一维

# arange([start,]stop[,step,], dtype=None)

>>>np.arange(10)

>>>[0 1 2 3 4 5 6 7 8 9]

>>>np.arange(2, 10, 2)

>>>[2 4 6 8]

# 使用ones创建全是1的数组

# np.ones(shape, dtype=None, order='C')

# shape:可以是一个int或一个元组

>>>np.ones(10)

>>>[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

>>>np.ones((2,3))

>>>[[1. 1. 1.]

[1. 1. 1.]]

# 使用ones_like创建形状相同的数组

# ones_like(a, dtype=float, order="C")

# a可以传一个数组,就会构造出一个形状类似的,全是1的array

np.ones_like(arr)

# zeros与zeros_like 与 ones 类似不做示例

# 使用full创建指定值的数组

# np.full(shape, fill_value, dtype=None, order="C")

# np.full_like(a, fill_value, dtype=None)

>>>np.full(10, 666)

>>>[666 666 666 666 666 666 666 666 666 666]

>>>np.full((2,4), 333)

>>>[[333 333 333 333]

[333 333 333 333]]

# 使用random模块生成随机数的数组

# randn(d0, d1, ..., dn)

>>>np.random.randn()

>>>-0.7629845857512441

>>>np.random.randn(3)

>>>[-0.00510708 -2.20612566 -0.95968755]

>>>np.random.randn(3, 2)

>>>[[ 0.22522444 1.41121834]

[-1.43390001 0.59619163]

[-0.8548558 0.67106487]]

>>>np.random.randn(3, 2, 4)

>>>[[[ 0.85228892 -2.02937327 -1.20477126 -1.05451308]

[-0.08425865 -1.75164644 -0.2093438 -1.60749571]]

[[-0.33571082 1.61433697 -0.53885548 -1.50995227]

[-0.99387774 -1.20473014 0.45910795 -0.34297335]]

[[-0.30997164 -1.13317638 -0.04083383 -0.91161322]

[ 1.24250354 0.58786012 -1.35684193 -1.61972877]]]

array 本身支持的大量操作和函数

直接逐元素的加减乘除等算数操作更好用的面向多维的数组索引求 sum / mean 等聚合函数线性代数函数、比如求解逆矩阵、求解方程组

+ - * / sin exp ...

三、Numpy对数组按索引查询

基础索引

与python List操作差不多,选择行选择列,切片…

神奇索引

用整数数组进性的索引

import numpy as np

x = np.arange(10)

>>>x

>>>[0 1 2 3 4 5 6 7 8 9]

>>>x[[3,4,7]]

>>>[3 4 7]

eg:获取数组中最大的前N个数字

arr = np.random.randint(1, 100, 10)

>>>arr

>>>[84 11 68 76 35 59 37 43 6 72]

>>>arr.argsort()[-3:] # 返回的是索引

>>>[9 3 0]

>>>arr[arr.argsort()[-3:]] # 根据索引可以找到那三个数

>>>[72 76 84]

二维数组

X = np.arange(20).reshape(4, 5)

>>>X

>>>[[ 0 1 2 3 4]

[ 5 6 7 8 9]

[10 11 12 13 14]

[15 16 17 18 19]]

>>>X[[0, 2]] # 省略了X[[0, 2], :]

>>>[[ 0 1 2 3 4]

[10 11 12 13 14]]

>>>X[:, [0, 2, 3]]

>>>[[ 0 2 3]

[ 5 7 8]

[10 12 13]

[15 17 18]]

>>>X[0, 2, 3], [1, 3, 4]

>>>[1, 13, 19]

布尔索引

布尔索引选择的数据是数组的拷贝

x = np.arange(10)

>>>x > 5

>>>[False False False False False False True True True True]

>>>x[x > 5]

>>>[6 7 8 9]

x[x <= 5] = 0

x[x > 5] = 1

>>>x

>>>[0 0 0 0 0 0 1 1 1 1]

四、Numpy常用random随机函数

rand(d0, d1, …, dn)

返回数据在(0,1)之间,具有均匀分布

>>>np.random.rand(5)

>>>[0.8324828 0.92545031 0.22392077 0.36862874 0.71133456]

>>>np.random.rand(3, 4)

>>>[[0.69471233 0.82112934 0.42856328 0.04320902]

[0.133817 0.98333428 0.85632542 0.88262798]

[0.20354067 0.79262774 0.81649079 0.09603552]]

randn(d0, d1, …, dn)

返回数据具有正态分布(均值0,方差1)

>>>np.random.randn(5)

>>>[-0.1286805 0.93223358 0.27559175 -1.16973075 0.66517628]

randin(low[, high, size, dtype])

生成随机整数,包含low,不包含high

如果high不指定,则从[0, low)中生成数字

>>>np.random.randint(10, 30, size=(2, 3))

>>>[[18 10 17]

[17 22 29]]

random([size])

生成 [ 0.0, 1.0 ) 的随机数

>>>np.random.random(size=(3, 4))

>>>[[0.23167487 0.31671224 0.55132212 0.08734653]

[0.64414045 0.92701402 0.90493366 0.19363701]

[0.01143492 0.38883903 0.61216406 0.67085381]]

choice(a[, size, replace, p])

a是一维数组,从它里面生成随机结果

>>>np.random.choice(5, size=(3, 4))

>>>[[4 0 2 1]

[2 3 1 0]

[4 2 0 2]]

>>>np.random.choice([1, 5, 6, 8, 7, 2, 5], size=(3, 4))

>>>[[7 5 8 6]

[1 1 7 1]

[1 5 1 6]]

shuffle(x)

把一个数组x进行随机排列,二维只打乱行,列不变

a = np.arange(10)

np.random.shuffle(a)

>>>a

>>>[8 6 2 7 5 3 0 9 4 1]

a = np.arange(20).reshape(4, 5)

np.random.shuffle(a)

>>>a

>>>[[ 5 6 7 8 9]

[ 0 1 2 3 4]

[15 16 17 18 19]

[10 11 12 13 14]]

permutation(x)

把一个数组x进行随机排列,或者数字全排列

normal([loc, scale, size])

按照平均值 loc 和方差 scale 生成高斯分布的数字

uniform([low, high, size])

在[low, high)之间生成均匀分布的数字

实例:对数组加入随机噪声

import numpy as np

import matplotlib.pyplot as plt

# 绘制sin曲线

x = np.linspace(-10, 10, 100)

y = np.sin(x)

plt.subplot(2, 1, 1)

plt.plot(x, y)

# 加入噪声

x = np.linspace(-10, 10, 100)

y = np.sin(x) + np.random.rand(len(x))

plt.subplot(2, 1, 2)

plt.plot(x, y)

plt.show()

五、Numpy的数学统计函数

Numpy有哪些数学统计函数

函数名说明np.sum所有元素的和np.prod所有元素的乘积np.cumsum元素的累积加和np.cumprod元素的累积乘积np.min最小值np.max最大值np.percentile0-100百分位数np.quantile0-1分位数np.median中位数np.average加权平均,参数可以指定weightsnp.mean平均值np.std标准差np.var方差

import numpy as np

arr = np.arange(12).reshape(3, 4)

# percentile 用法与 quantile 用法类似

>>>np.percentile(arr, [25, 50, 75])

>>>[2.75 5.5 8.25]

# average用法,weights的形式要与矩阵的shape一样

weights = np.random.rand(*arr.shape)

>>>np.average(arr, weights=weights)

>>>4.769350585540324

Numpy的 axis 参数的用途

axis=0 代表行、axis=1 代表列

对于 sum / mean / media 等聚合函数:

理解1:axis=0 代表把行消解掉,axis=1 代表把列消解掉 理解2:axis=0 代表跨行计算,axis=1 代表跨列计算

import numpy as np

arr = np.arange(12).reshape(3, 4)

>>>arr

>>>[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

# 列相加,行消解掉了

>>>arr.sum(axis=0)

>>>[12 15 18 21]

>>>arr.sum(axis=1)

>>>[6 22 38]

# 其他函数也同理

实例:机器学习将数据进行标准化

arr 对应到现实世界的一种解释:

行:每行对应一个样本数据列:每列代表样本的一个特征

数据标准化:

对于机器学习、神经网络来说,不同列的量纲应该相同,训练收敛的更快;比如商品的价格是0到100元、销量是1万到10万个,这俩数字没有可比性,因此需要先都做标准化;不同列代表不同的特征,因此需要axis=0做计算标准化一般使用A = (A - mean(A, axis=0)) / std(A, axis=0)公式进行

标准化公式:

z

=

x

−

μ

σ

标准化公式: z = \frac{x - \mu}{\sigma}

标准化公式:z=σx−μ​

import numpy as np

arr = np.arange(12).reshape(3, 4)

>>>arr

>>>[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

# 计算每列的均值

mean = np.mean(arr, axis=0)

>>>mean

>>>[4. 5. 6. 7.]

# 计算每列的方差

std = np.std(arr, axis=0)

>>>std

>>>[3.26598632 3.26598632 3.26598632 3.26598632]

# 计算结果

result = (arr - mean)/std

>>>result

>>>[[-1.22474487 -1.22474487 -1.22474487 -1.22474487]

[ 0. 0. 0. 0. ]

[ 1.22474487 1.22474487 1.22474487 1.22474487]]

六、Numpy怎样给数组增加一个维度

背景

很多数据计算都是二维或三位的,对于一维的数据输入为了形状匹配,经常需升维变成二维

需要

在不改变数据的情况下,添加数组维度;(注意观察这个例子,维度变了,但数据不变)

原始数组:一维数组arr=[1,2,3,4],其shape是(4,),取值分别为arr[0],arr[1],arr[2],arr[3]

变形数组:二维数组arr[[1,2,3,4]],其shape实(1,4),取值分别为a[0,0],a[0,1],a[0,2],a[0,3]

实操

经常需要在纸上手绘数组的形状,来查看不同数组是否形状匹配,是否需要升降维度。

3种方法

np.newaxis:关键字,使用索引的语法给数组添加维度np.expand_dims(arr, axis):方法,和 np.newaxis 实现一样的功能,给 arr 在 axis 位置添加维度np.reshape(arr, newshape):方法,给一个维度设置为1完成升维

import numpy as np

arr = np.arange(5)

>>>arr

>>>[0 1 2 3 4]

# 当前是一维向量

>>>arr.shape

>>>(5, )

方法1:np.newaxis关键字

注意:np.newaxis 其实就是 None 的别名

>>>np.newaxis == None

>>>True

>>>np.newaxis is None

>>>True

说明以下所有的np.newaxis的位置,都可以用None替代

给一维向量添加一个行维度

>>>arr[np.newaxis, :]

>>>[[0 1 2 3 4]]

>>>arr[np.newaxis, :].shape

>>>(1, 5)

给一维向量添加一个列维度

>>>arr[:, np.newaxis]

>>>[[0]

[1]

[2]

[3]

[4]]

>>>arr[:, np.newaxis].shape

>>>(5, 1)

方法2:np.expand_dims方法

np.expand_dims方法实现的效果,和np.newaxis关键字是一模一样的

给一维数组添加一个行维度

相当于arr[np.newaxis, arr]

# 与上面结果是一样的,不作打印了

np.expand_dims(arr, axis=0)

np.expand_dims(arr, axis=0).shape

给一维数组添加一个列维度

相当于arr[arr, np.newaxis]

np.expand_dims(arr, axis=1)

np.expand_dims(arr, axis=1).shape

方法3:np.reshape方法

给一维数组添加一个行维度

# 这两种方式输出一致,一般使用第二种。

# 括号的两个参数分别的行和列的个数,-1代表自己算出需要的行/列数

>>>np.reshape(arr, (1, 5))

>>>np.reshape(arr, (1, -1))

>>>[[0 1 2 3 4]]

给一维数组添加一个列维度

>>>np.reshape(arr, (-1, 1))

>>>np.reshape(arr, (-1, 1)).shape

七、Numpy的数组合并操作

背景

在给机器学习准备数据的过程中,经常需要进行不同来源的数据合并的操作。

两类场景

给已有的数据添加多行,比如增添一些样本数据进去;给已有的数据添加多列,比如增添一些特征进去;

以下操作均可以实现数组合并

np.concatenate(array_list, axis=0/1):沿着指定axis进行数组的合并np.vstack 或者 np.row_stack(array_list) :垂直 vertically、按行 row wise 进行数据合并np.hstack 或者 np.column_stack(array_list) :水平 horizontally、按列 column wise 进行数据合并

import numpy as np

a = np.arange(6).reshape(2, 3)

b = np.random.randint(10, 20, size=(4, 3))

>>>a

>>>[[0 1 2]

[3 4 5]]

>>>b

>>>[[12 13 17]

[17 19 11]

[18 18 15]

[10 16 15]]

按行合并

# 方法一

np.concatenate([a, b])

# 方法二

np.vstack([a, b])

# 方法三

np.row_stack([a, b])

# 输出结果一致

>>>[[ 0 1 2]

[ 3 4 5]

[12 13 17]

[17 19 11]

[18 18 15]

[10 16 15]]

import numpy as np

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

b = np.random.randint(10, 20, size=(3, 2))

>>>a

>>>[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]] 拼多多帮助力入口

>>>b

>>>[[10 10]

[10 17]

[10 17]]

按列合并

# 方法一

np.concatenate([a, b], axis=1)

# 方法二

np.hstack([a, b])

# 方法三

np.column_stack([a, b])

# 打印结果

>>>[[ 0 1 2 3 10 10]

[ 4 5 6 7 10 17]

[ 8 9 10 11 10 17]]

由如上视频做的笔记:Numpy非常重要的数据合并操作_哔哩哔哩_bilibili

python 机器学习---Numpy学习

推荐链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧