python-numpy整理

python-numpy整理

一.numpy \textbf{一.numpy} .numpy

1.创建数组

(1)创建单位矩阵 ( n u m p y . i d e n t i t y ) (numpy.identity) (numpy.identity)

import numpy as np
array = np.identity(4)
print(array)

在这里插入图片描述

(2)创建任意shape的全零多维数组 ( n u m p y . z e r o s ) (numpy.zeros) (numpy.zeros)

import numpy as np
# 提供列表或元组类型的shape
array = np.zeros((1, 2, 3))
print(array)
array = np.zeros([1, 2, 3])
print(array)

在这里插入图片描述

(3)创建任意shape的标准正态分布的多维数组 ( n u m p y . r a n d o m . r a n d n ) (numpy.random.randn) (numpy.random.randn)

# 提供shape是一个个整数,不能是list或tuple
import numpy as np
array = np.random.randn(3, 3)
print(array)

在这里插入图片描述

(4)创建任意shape的0到1的随机多维数组 ( n u m p y . r a n d o m . r a n d ) (numpy.random.rand) (numpy.random.rand)

import numpy as np
array = np.random.rand(3, 4)
print(array)

在这里插入图片描述
另一种:

import numpy as np
array = np.random.random((3, 4))
print(array)

唯一的区别在于提供shape的方式不一样。
在这里插入图片描述

(5)创建任意shape的low到high的随机整型多维数组 ( n u m p y . r a n d o m . r a n d i n t ) (numpy.random.randint) (numpy.random.randint)

import numpy as np
array = np.random.randint(low=1, high=4, size=(3, 4, 4))
print(array)

在这里插入图片描述

(6)创建任意shape的空的多维数组 ( n u m p y . e m p t y ) (numpy.empty) (numpy.empty)

import numpy as np
array = np.empty((2, 2, 2))
print(array)

在这里插入图片描述

(7)创建一个一维数组,其元素为指定间隔内均匀间隔的数字 ( n u m p y . l i n s p a c e ) (numpy.linspace) (numpy.linspace)

import numpy as np
print(np.linspace(start=1, stop=100, num=10))
print(np.linspace(start=1, stop=100, num=10).shape)

在这里插入图片描述

2.常用数组操作

(1)按行按列拼接 ( n u m p y . v s t a c k 、 n u m p y . h s t a c k 、 n u m p y . c o l u m n s t a c k ) (numpy.vstack、numpy.hstack、numpy.column_stack) (numpy.vstacknumpy.hstacknumpy.columnstack)

import numpy as np

array1 = np.random.randint(1, 4, (2, 4, 5))
array2 = np.random.randint(5, 6, (2, 4, 5))

# 按行拼接
new_array = np.vstack((array1, array2, array2))
print(new_array.shape)
# 按列拼接
new_array = np.hstack((array1, array2, array2))
print(new_array.shape)

在这里插入图片描述

    vstack和hstack允许提供多维数组在第一个维度和第二个维度上的拼接,而且不限制多维数组的个数,要求就是在拼接时多维数组除了拼接维度可以不一样以外,其他维度必须保持一致。

    另一个按列拼接的函数是column_stack,和hstack是差不多的,它们是有区别的,我以前在使用时有时候hstack是用不了的,但是column_stack是用不了的,具体原因记不到了,如果hstack用不了就试试column_stack吧。

import numpy as np
array1 = np.random.randint(1, 4, (2, 4, 5, 5))
array2 = np.random.randint(5, 6, (2, 4, 5, 5))
new_array = np.column_stack((array1, array2, array1, array2))
print(new_array.shape)

在这里插入图片描述

(2)数组转置 ( a r r a y . T ) (array.T) (array.T)

    支持任意shape的numpy数组进行转置。

import numpy as np

array1 = np.random.randint(1, 10, size=(2, 3, 4))
array2 = tc.randint(1, 10, size=(2, 3, 4, 5))

print(array1.shape)
array1 = array1.T
print(array1.shape)
array1 = array1.T
print(array1.shape)
array1 = array1.T
print(array1.shape)

在这里插入图片描述

(3)多维数组维度切换 ( n u m p y . t r a n s p o s e ) (numpy.transpose) (numpy.transpose)

    不提供axes则与T同样效果,提供axes可以对任意维度进行维度转换。

import numpy as np
import torch as tc

array1 = np.random.randint(1, 10, size=(2, 3, 4))
array2 = tc.randint(1, 10, size=(2, 3, 4, 5))

print(array1.shape)
array1 = np.transpose(array1)
print(array1.shape)
array1 = np.transpose(array1, axes=[0, 2, 1])
print(array1.shape)

在这里插入图片描述

(4)消除数组中维数为1的维度 ( n u m p y . s q u e e z e ) (numpy.squeeze) (numpy.squeeze)

import numpy as np

array1 = np.random.randint(1, 10, size=(2, 3, 1, 4, 1))
print(array1.shape)
print(np.squeeze(array1).shape)

在这里插入图片描述

(5)改变数组shape ( n u m p y . r e s h a p e ) (numpy.reshape) (numpy.reshape)

import numpy as np

array1 = np.random.randint(1, 10, size=(2, 3, 1, 4, 1))
print(array1.shape)
print(np.reshape(array1, newshape=(3, 8)).shape)

在这里插入图片描述

(6)将相同shape的两个数组中的元素放到1个一维数组中 ( n u m p y . a p p e n d ) (numpy.append) (numpy.append)

    将后一个数组的元素加到前一个数组的元素后面。

import numpy as np

array1 = np.random.randint(1, 10, size=(3, 2, 3))
print(array1.shape)
array1 = np.append(array1, array1)
print(array1.shape)

在这里插入图片描述

(7)返回满足条件的索引 ( n u m p y . w h e r e ) (numpy.where) (numpy.where)

import numpy as np

array1 = np.random.randint(1, 10, size=(3, 2))
print(array1)
# 获取大于5的元素的索引并提取出来
print(np.where(array1 > 5))
print(array1[np.where(array1 > 5)])
# 将大于5的转换为1,否则为0
print(np.where(array1 > 5, 1, 0))

在这里插入图片描述

(8)获取数组形状、大小和维度数量 ( n u m p y . s h a p e 和 n u m p y . s i z e ) (numpy.shape和numpy.size) (numpy.shapenumpy.size)

import numpy as np

array1 = np.random.randint(1, 10, size=(2, 3, 4))
print(array1.shape)
print(array1.size)
print(np.ndim(array1))

在这里插入图片描述

3.数组计算

(1)奇异值分解 ( n u m p y . l i n a l g . s v d ( 张 量 或 n u m p y 数 组 ) ) (numpy.linalg.svd(张量或numpy数组)) (numpy.linalg.svd(numpy))

import numpy as np
import torch as tc
import numpy.linalg as linalg

array1 = np.random.randint(1, 10, size=(3, 4))
array2 = np.random.randint(1, 10, size=(3, 4, 5, 6))
array3 = tc.randint(1, 10, size=(3, 4, 5))
array4 = tc.randint(1, 10, size=(3, 4, 5))

u, s, v = linalg.svd(array1)
print(u.shape, s.shape, v.shape)
u, s, v = linalg.svd(array2)
print(u.shape, s.shape, v.shape)
u, s, v = linalg.svd(array3)
print(u.shape, s.shape, v.shape)
u, s, v = linalg.svd(array4)
print(u.shape, s.shape, v.shape)

    奇异矩阵在这是奇异向量,该svd不只适用于numpy,也适用于torch,其实numpy和torch之间很多都是互通的。
在这里插入图片描述

(2)求范数 ( n u m p y . l i n a l g . n o r m ( d , o r d = 1 ) 可 任 意 s h a p e ) (numpy.linalg.norm(d, ord=1) 可任意shape) (numpy.linalg.norm(d,ord=1)shape)

    d为输入数组或张量(只能是一维或二维),ord为1代表求1-范数,ord为2代表求2-范数,不提供ord默认为求2-范数。

import numpy as np
import torch as tc
import numpy.linalg as linalg

array1 = np.random.randint(1, 10, size=(2, 3))

print(array1)
norm = linalg.norm(array1, ord=1)
print(norm)
norm = linalg.norm(array1, ord=2)
print(norm)
norm = linalg.norm(array1[0], ord=1)
print(norm)
norm = linalg.norm(array1[0], ord=2)
print(norm)

在这里插入图片描述

(3)求内积 n u m p y . v d o t ( 数 组 或 张 量 , 数 组 或 张 量 ) numpy.vdot(数组或张量,数组或张量) numpy.vdot(,)

    支持任意shape求内积

import numpy as np
import torch as tc

array1 = np.random.randint(1, 10, size=(2, 3, 2, 2))
array4 = tc.randint(1, 10, size=(2, 3, 2, 2))

print(array1)
print(array4)
vdot = np.vdot(array1, array4)
print(vdot)
vdot = np.vdot(array1[:, :, :, 0], array4[:, :, :, 0])
print(vdot)
vdot = np.vdot(array1[:, :, 0], array4[:, :, 0])
print(vdot)

(4)求向量中所有元素的乘积 ( n u m p y . p r o d ) (numpy.prod) (numpy.prod)

    支持numpy数组任意shape求所有元素的乘积,不能tensor类型。

import numpy as np
import torch as tc


array1 = np.random.randint(1, 10, size=(2, 2, 2, 2))
array4 = tc.randint(1, 10, size=(2, 2, 2))

print(array1)
print(np.prod(array1))
print(array4)
# 报错
# print(np.prod(array4))

在这里插入图片描述

(5)numpy简单计算 ( n u m p y . a b s 、 n u m p y . s q r t 、 n u m p y . m a x 、 n u m p y . m e a n 、 n u m p y . s t d 、 n u m p y . s u m ) (numpy.abs、numpy.sqrt、numpy.max、numpy.mean、numpy.std、numpy.sum) (numpy.absnumpy.sqrtnumpy.maxnumpy.meannumpy.stdnumpy.sum)

import numpy as np

array1 = np.random.randint(-6, 6, size=(3, 2))

print(np.abs(array1))
print(np.sqrt(abs(array1)))

# 均可指定维度:最大值、均值、标准差、总和
# 也可以直接对整体进行操作
print(np.max(array1))
print(np.mean(array1))
print(np.std(array1))
print(np.sum(array1))
print(np.max(array1, axis=1))
print(np.mean(array1, axis=1))
print(np.std(array1, axis=1))
print(np.sum(array1, axis=1))

在这里插入图片描述

(6)矩阵乘积和矩阵对应元素相乘 ( n u m p y . m a t m u l 、 n u m p y . m u l t i p l y ) (numpy.matmul、numpy.multiply) (numpy.matmulnumpy.multiply)

    matmul支持两个矩阵相乘,维度不能超过二维,multiply支持任意相同shape的任意数量数组进行Hadamard乘积(对应位置元素相乘)

import numpy as np
array1 = np.random.randint(-6, 6, size=(3, 2))
print("array1:", array1)
print(np.matmul(array1, array1.T))
print(np.multiply(array1, array1, array1))

在这里插入图片描述

(7)共轭 ( n u m p y . c o n j ) (numpy.conj) (numpy.conj)

import numpy as np

array1 = np.random.randint(-6, 6, size=(3, 2)) + 2j
print(array1)
print(np.conj(array1))

在这里插入图片描述

(8)求迹(numpy.trace)

    支持2维和3维数组求迹,3维数组实际上是批量求矩阵的迹然后放在一维数组中。

import numpy as np

array1 = np.random.randint(3, 6, size=(2, 3))
array2 = np.random.randint(3, 6, size=(2, 3, 6))

print(array1)
print(np.trace(array1))
print(array2)
print(np.trace(array2))

在这里插入图片描述

(9)爱因斯坦求和约定 ( n u m p y . e n i s u m ) (numpy.enisum) (numpy.enisum)

    enisum可以完成前面提到的大部分操作,只要对提供的数组用字母进行了标记。建议在指定subscripts时显式指定,即使用’->’,因为这样易读。下面是一些基本的使用,可以看到该函数可以实现很多前面许多函数的功能。

import numpy as np

array1 = np.random.randint(3, 6, size=(2, 3))
array2 = np.random.randint(3, 6, size=(2, 3, 6))
array3 = np.random.randint(3, 6, size=(4, 4))
array4 = np.random.randint(3, 6, size=(4, 4, 5, 6, 7))

print("array1_shape:", array1.shape, "array2_shape:", array2.shape)
# 任意维度缩并
print("\n任意维度缩并:")
print(np.einsum("ij, ijl->l", array1, array2).shape)

# 任意维度外积
print("\n任意维度外积:")
print(np.einsum("ij, xyz->ijxyz", array1, array2).shape)

# hardmard积
print("\narray1:", array1)
print("array1求hardmard积:")
print(np.einsum('ij,ij->ij', array1, array1))
# 矩阵求迹
print("\narray3:", array3)
print("array3矩阵求迹:")
print(np.einsum(array3, [0, 0]))
# np.einsum("ii", array33)也可以求迹

# 求对角线上的元素
print("\narray3求对角线上的元素:")
print(np.einsum(array3, [0, 0], [0]))
# np.einsum('ii->i', array3)也可以求对角线上的元素
# 维度转换
print("\narray2维度转换:")
print(np.einsum("ijk->kij", array2).shape)

# 省略号
print("\narray4_shape:", array4.shape)
print("array4 省略号代替其他未写的指标:")
print(np.einsum("i...", array4).shape)
print(np.einsum("...i", array4).shape)
print(np.einsum("i...->...", array4).shape)
print(np.einsum("i...k->...", array4).shape)

# 求和(变相的缩并)
print("\n求和(变相的缩并):")
print(np.einsum("ijk->i", array2))

在这里插入图片描述
在这里插入图片描述

二.拓展 \textbf{二.拓展} .拓展

(1)tensor与numpy之间的转换

将numpy数组a转换为tensor

b=torch.from_numpy(a)

将tensor转换为numpy数组

b = a.numpy()

(2)ncon.ncon

    这个函数与einsum函数的区别主要在于把字母换成了数字,是很类似的。

import numpy as np
from numpy import linalg as LA
from ncon import ncon

# 初始化张量
d = 2
chi = 10
# 10*2*10
A = np.random.rand(chi, d, chi)
B = np.random.rand(chi, d, chi)

# 设置辅助指标,两种辅助指标,分别是Sab和Sba
# 10
sAB = np.ones(chi) / np.sqrt(chi)
sBA = np.ones(chi) / np.sqrt(chi)

# 10*10
sigBA = np.random.rand(chi, chi)
tol = 1e-10

# 初始化张量网络
# 10*10 10*10 10*2*10 10*2*10 10*10 10*10 10*2*10 10*2*10
tensors = [np.diag(sBA), np.diag(sBA), A, A.conj(), np.diag(sAB),
           np.diag(sAB), B, B.conj()]

labels = [[1, 2], [1, 3], [2, 4], [3, 5, 6], [4, 5, 7], [6, 8], [7, 9], [8, 10, -1], [9, 10, -2]]
# 10*10 10*10 10*10 10*2*10 10*2*10 10*10 10*10 10*2*10 10*2*10
sigBA_new = ncon([sigBA, *tensors], labels)
print(sigBA_new.shape)

三.如遇其他函数,就会整理到上面 \textbf{三.如遇其他函数,就会整理到上面} .如遇其他函数,就会整理到上面

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NumPy是一个功能强大的Python库,主要用于对多维数组执行计算。它的使用可以使代码更简洁,并且具有一些特性,如向量化操作,可以加速计算过程。在NumPy中,最重要的数据结构是NumPy数组,它可以通过不同的方法进行创建。 创建一维NumPy数组的常见方法有以下几种: 1. 使用np.array()函数,传入一个列表作为参数,例如: my_array = np.array([1, 2, 3, 4, 5]) 2. 使用np.array()函数,传入一个元组作为参数,例如: my_array2 = np.array((0, 1, 2, 3, 4)) 3. 使用np.arange()函数,该函数类似于内置函数range(),返回一个数组而不是列表,例如: my_array3 = np.arange(5) 4. 使用np.linspace()函数,该函数返回一个包含指定数量元素的数组,而不是指定步长(step),例如: my_array4 = np.linspace(0, 2*np.pi, 5) 这些方法可以用来创建不同类型的一维NumPy数组。通过打印数组可以查看创建的结果。在使用NumPy之前,需要导入NumPy库,可以使用import numpy as np语句进行导入。 NumPy还可以用于执行各种数学任务,如数值积分、微分、内插、外推等,以及快速处理图像等。因此,在机器学习中,NumPy常被用于存储训练数据和机器学习模型的参数,以及进行简单和快速的计算。 总结起来,NumPy提供了丰富的功能和优秀的库函数,使得在Python中进行数值计算变得更加方便和高效。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python科学计算的基本包-Python科学计算基本包Numpy使用的教程.pdf](https://download.csdn.net/download/qq_43934844/87898289)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [numpy基础语法整理](https://blog.csdn.net/weixin_61890283/article/details/124596265)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值