Python Ecosystem之Numpy使用记录

Numpy中的常用操作

np.logical_and(y>=0, y<=5)
  • 生成随机的整数索引
# 方式一
tmp_a = np.arange(10)
np.random.shuffle(tmp_a)
tmp_a
Out[16]: array([4, 0, 8, 1, 6, 7, 3, 9, 5, 2])
# 方式二
np.random.permutation(range(10))
Out[17]: array([9, 3, 7, 6, 5, 4, 1, 8, 0, 2])

  • np.linspace()
tmp_a = np.linspace(50, 95,int(np.round((0.95 - .5) / .05)) + 1, endpoint=True) / 100
Out[13]: array([0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 , 0.95])
# 奇怪的是tmp_b中得到的tmp_b[8]并不等于0.9
tmp_b = np.linspace(.5, 0.95,int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)
Out[14]: array([0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 , 0.95])

tmp_a - tmp_b
Out[26]: 
array([0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
       0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
       1.11022302e-16, 0.00000000e+00])
np.where(.8 == tmp_a)[0], np.where(.9 == tmp_a)[0]
Out[27]: (array([6]), array([8]))
np.where(.8 == tmp_b)[0], np.where(.9 == tmp_b)[0]
Out[28]: (array([6]), array([], dtype=int64))

numpy.random.RandomState(seed=None)

  RandomStateGenerator类中有多种方法,可用于从各种概率分布中生成随机数。类中的每个方法除了包含有特定于分布的参数外,还都包含有1个关键字参数size,其默认值为None;如果size为None,则生成并返回单个值;如果size为整数(integer),则返回1个填充有生成值的一维数组;如果size为元组(tuple),则返回1个填充有生成值并具有该形状的多维数组。
  Compatibility Guarantee: A fixed bit generator using a fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect.
  class numpy.random.RandomState(seed=None)的应用场景:

import numpy as np

SEED = 23455  # 设置seed值,生成ndarray对象
# rdm = np.random.RandomState(SEED)  # 基于seed产生随机数; 这两个语句等价
rdm = np.random.mtrand.RandomState(SEED)  # 基于seed产生随机数; 这两个语句等价
X = rdm.rand(32, 2)  # rand函数产生随机数, 返回shape大小为(32,2)的随机数组, 取值在0~1之间
print("X:\n",X)

Legacy Random Generation — NumPy v1.19 Manual
NEP 19 — Random Number Generator Policy — NumPy Enhancement Proposals
numpy中的np.random.mtrand.RandomState_weixin_30725467的博客20181028
【数据处理】Numpy.random.seed()的用法_白糖炒栗子 20180602
【数据处理】numpy.random.RandomState的用法_白糖炒栗子 20180602

数组的获取

获取数组是通过索引 (indexing) 和切片 (slicing) 来完成的,

  • 切片是获取一段特定位置的元素
  • 索引是获取一个特定位置的元素
  • 切片得到的是原数组的一个视图 (view),通过赋值给另一个变量来 修改切片中的内容会改变原数组;
  • 索引得到的是原数组的一个复制 (copy),通过赋值给另一个变量来 修改索引中的内容不会改变原数组;
  • 直接对原数组的切片/索引数据赋值,会改变原数组;
temp = np.arange(5)
index_1 = temp[2]  # 2
index_1 = 10
temp  # array([0, 1, 2, 3, 4])
slice_1 = temp[3:4] # array([3])
slice_1[0] = 100 
temp  # array([0, 1, 2, 100, 4])
slice_2 = temp[3:4] # array([100])
slice_2 = 1000 
temp  # array([0, 1, 2, 100, 4])
——————分割线——————
temp = np.arange(5)
temp[0] = 10
temp  # array([10, 1, 2, 3, 4])
temp[2:3] = 100
temp  # array([10, 1, 100, 3, 4])

正规索引

numpy取数组中的行和列_qq_44812523的博客-CSDN博客 20200710

a = torch.arange(60).reshape((5, 3, 4))
print(a[2:4].size())
print(a[2:4][0:2].size())
print(a[2:4][0:2][0].size())
print(a[2:4, 0:2].size())
print(a[2:4, 0:2, 0].size())
print(a[2:4, 0:2, 0])
a[2:4, 0:2, 0] = -1
b = a.clone()
print('b的值:', '\n', b)

Numpy中打印数值输出时的格式控制

Python编程:如何规范numpy中数组元素的打印输出格式 - 云+社区 - 腾讯云 20190420

Numpy线性代数

线性代数(numpy.linalg) | NumPy 中文

numpy.log()和math.log()

  numpy.log()和math.log()都可以进行对数运算。
  但math.log()只能对单个数值 (scalar) 进行运算,如果对数组运算则会报错:TypeError: only size-1 arrays can be converted to Python scalars;
  而numpy.log()则可以对数组进行运算。
  因此,建议用numpy.log(),少用math.log()。

numpy.arctan()和numpy.arctan2()

Numpy中arctan和arctan2的区别_SH_13的博客-CSDN博客 20200427

SciPy使用之求函数的导数

SciPy函数求导数 - Python学习园

alpha = Symbol('alpha')  # 或者使用alpha = symbols('alpha')
x = Symbol('x')  # 或者使用x = symbols('x')
# 或者使用alpha, x = symbols('alpha, x')
# diff_pos_fl = diff(- alpha * (x ** 2) * log(x), x)  # 关于x的偏导函数, 包含alpha参数
# diff_pos_fl = diff(- alpha * (x ** 2) * log(x), x).subs(alpha, 1.0)  # 关于x的偏导函数, 在alpha参数等于1.0时
diff_pos_fl = diff(- alpha * (x ** 2) * log(x), x).subs(alpha, 1.0).subs(x, 0.3)  # 在x=0.3处的偏导数, 在alpha参数等于1.0时
print(diff_pos_fl)

np.save()

问题记录

问题描述
  开始
原因分析:
  开始
解决方案:
  开始

将ndarray数值保存到.txt中时报错TypeError: can only concatenate str (not "numpy.float32") to str

问题描述

import numpy as np
tmp_a = np.arange(5).astype(np.float32)

for i in range(len(tmp_a)):
    with open('./tmp_data_saved.txt', 'a') as f:
        f.write(f'tmp_a{i}\t' + tmp_a[i] + '\n')

print('\nfinish!')

# 原始代码 f.write(f'tmp_a{i}\t' + tmp_a[i] + '\n') 会报以下错误:
Traceback (most recent call last):
  File "d:/WorkSpace/Pytorch_WorkSpace/PythonTest/test_002.py", line 11, in <module>
    f.write(f'tmp_a{i}\t' + tmp_a[i] + '\n')
TypeError: can only concatenate str (not "numpy.float32") to str

原因分析and解决方案:
  tmp_a[i]的数据类型是numpy.float32,无法直接保存到.txt中;解决方案是利用str()函数将其转换为str类型后再保存;

import numpy as np
tmp_a = np.arange(5).astype(np.float32)

for i in range(len(tmp_a)):
    with open('./tmp_data_saved.txt', 'a') as f:
        f.write(f'tmp_a{i}\t' + str(tmp_a[i]) + '\n')

print('\nfinish!')

# tmp_data_saved.txt中的内容如下:
tmp_a0	0.0
tmp_a1	1.0
tmp_a2	2.0
tmp_a3	3.0
tmp_a4	4.0

TODO:浮点数显示为xxx.999…999或xxx.000…000

20210916记:

ImportError: numpy.core.multiarray failed to import

问题描述
  20230413记:ImportError: numpy.core.multiarray failed to import
原因分析and解决方案:

AttributeError: module ‘numpy’ has no attribute ‘MachAr’

问题描述
  20230413记:AttributeError: module 'numpy' has no attribute 'MachAr'
原因分析and解决方案:
  I had this issue while running import statsmodels.api as sm. The issue was happening with numpy==1.24.2. Downgrading it to 1.23 solved the issue for me. I have not tested newer versions tbh, so another one might work as well.

待补充

  

待补充

  



文字居中

数学公式粗体 \textbf{} 或者 m e m o r y {\bf memory} memory
数学公式粗斜体 \bm{}

摘录自“bookname_author”
此文系转载,原文链接:名称 20200505

高亮颜色说明:突出重点
个人觉得,:待核准个人观点是否有误

分割线

分割线


我是颜色为00ffff的字体
我是字号为2的字体
我是颜色为00ffff, 字号为2的字体
我是字体类型为微软雅黑, 颜色为00ffff, 字号为2的字体

分割线

分割线
问题描述:
原因分析:
解决方案:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值