人工智能基础 - Numpy
  h9htfs4cnhmS 2023年12月06日 24 0

Numpy介绍

Numpy(Numerical Python)是一个开源的Python科学计算库,用于快速处理任意维度的数组。

Numpy支持常见的数组和矩阵操作。对于同样的数值计算任务,使用Numpy比直接使用Python要简洁的多。

Numpy使用ndarray对象来处理多维数组,该对象是一个快速而灵活的大数据容器。

ndarray介绍

NumPy提供了一个N维数组类型ndarray,它描述了相同类型的“items”的集合。

人工智能基础 - Numpy_Python

用ndarray进行存储:

import numpy as np

# 创建ndarray
score = np.array([[80, 89, 86, 67, 79],
[78, 97, 89, 67, 81],
[90, 94, 78, 67, 74],
[91, 91, 90, 67, 69],
[76, 87, 75, 67, 86],
[70, 79, 84, 67, 84],
[94, 92, 93, 67, 64],
[86, 85, 83, 67, 80]])

返回结果:

array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])

使用Python列表可以存储一维数组,通过列表的嵌套可以实现多维数组,那么为什么还需要使用Numpy的ndarray呢?

import random
import time
import numpy as np
a = []
for i in range(100000000):
    a.append(random.random())

# 通过%time魔法方法, 查看当前行的代码运行一次所花费的时间
%time sum1=sum(a)

b=np.array(a)

%time sum2=np.sum(b)

其中第一个时间显示的是使用原生Python计算时间,第二个内容是使用numpy计算时间:

CPU times: user 852 ms, sys: 262 ms, total: 1.11 s
Wall time: 1.13 s
CPU times: user 133 ms, sys: 653 µs, total: 133 ms
Wall time: 134 ms

从中我们看到ndarray的计算速度要快很多,节约了时间。

机器学习的最大特点就是大量的数据运算,那么如果没有一个快速的解决方案,那可能现在python也在机器学习领域达不到好的效果。

人工智能基础 - Numpy_数组_02

Numpy专门针对ndarray的操作和运算进行了设计,所以数组的存储效率和输入输出性能远优于Python中的嵌套列表,数组越大,Numpy的优势就越明显。

基本操作

生成数组

生成0和1的数组

  • np.ones(shape[, dtype, order])
  • np.ones_like(a[, dtype, order, subok])
  • np.zeros(shape[, dtype, order])
  • np.zeros_like(a[, dtype, order, subok])

从现有数组生成

  • np.array(object[, dtype, copy, order, subok, ndmin])
  • np.asarray(a[, dtype, order])

生成固定范围的数组

  • np.linspace (start, stop, num, endpoint)

生成等间隔的序列

start 序列的起始值
stop 序列的终止值,
num 要生成的等间隔样例数量,默认为50
endpoint 序列中是否包含stop值,默认为ture
# 生成等间隔的数组
np.linspace(0, 100, 11)

返回结果:

array([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.])
  • 其它的还有
  • numpy.arange(start,stop, step, dtype)
  • numpy.logspace(start,stop, num)
np.arange(10, 50, 2)

返回结果:

array([10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42,
       44, 46, 48])
# 生成10^x
np.logspace(0, 2, 3)

返回结果:

array([  1.,  10., 100.])

生成随机数组

  • np.random模块
  • np.random.rand(d0d1...dn)
    返回[0.0,1.0)内的一组均匀分布的数。
  • np.random.uniform(low=0.0high=1.0size=None)
    功能:从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
    参数介绍:
    low: 采样下界,float类型,默认值为0;
    high: 采样上界,float类型,默认值为1;
    size: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出mnk个样本,缺省时输出1个值。
    返回值:ndarray类型,其形状和参数size中描述一致。
  • np.random.randint(lowhigh=Nonesize=Nonedtype='l')
    从一个均匀分布中随机采样,生成一个整数或N维整数数组,取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
# 生成均匀分布的随机数
x1 = np.random.uniform(-1, 1, 100000000)

返回结果:

array([ 0.22411206,  0.31414671,  0.85655613, ..., -0.92972446,
0.95985223,  0.23197723])

数组的索引、切片

  • 获取第一个股票的前3个交易日的涨跌幅数据
# 二维的数组,两个维度 
stock_change[0, 0:3]

返回结果:

array([-0.03862668, -1.46128096, -0.75596237])

一维、二维、三维的数组如何索引?

# 三维,一维
a1 = np.array([ [[1,2,3],[4,5,6]], [[12,3,34],[5,6,7]]])
# 返回结果
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[12,  3, 34],
        [ 5,  6,  7]]])
# 索引、切片
>>> a1[0, 0, 1]   # 输出: 2

形状修改

让刚才的股票行、日期列反过来,变成日期行,股票列

  • ndarray.reshape(shape[, order]) Returns an array containing the same data with a new shape.
# 在转换形状的时候,一定要注意数组的元素匹配
stock_change.reshape([10, 8])
stock_change.reshape([-1,20])  # 数组的形状被修改为: (4, 20), -1: 表示通过待计算
  • ndarray.resize(new_shape[, refcheck]) Change shape and size of array in-place.
stock_change.resize([10, 8])
  • ndarray.T 数组的转置
  • 将数组的行、列进行互换
stock_change.shape
(10, 8)
stock_change.T.shape
(8, 10)

类型修改

  • ndarray.astype(type)
stock_change.astype(np.int32)
  • ndarray.tostring([order])或者ndarray.tobytes([order]) Construct Python bytes containing the raw data bytes in the array.
  • 转换成bytes
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[12, 3, 34], [5, 6, 7]]])
arr.tostring()

## 数组的去重

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月06日 0

暂无评论

推荐阅读
h9htfs4cnhmS