GVKun编程网logo

Python 列表比 numpy 数组表现更好? Python 列表麻木(python列表和数组有啥区别)

3

本文将分享Python列表比numpy数组表现更好?Python列表麻木的详细内容,并且还将对python列表和数组有啥区别进行详尽解释,此外,我们还将为大家带来关于"importnumpyasnp"

本文将分享Python 列表比 numpy 数组表现更好? Python 列表麻木的详细内容,并且还将对python列表和数组有啥区别进行详尽解释,此外,我们还将为大家带来关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”的相关知识,希望对你有所帮助。

本文目录一览:

Python 列表比 numpy 数组表现更好? Python 列表麻木(python列表和数组有啥区别)

Python 列表比 numpy 数组表现更好? Python 列表麻木(python列表和数组有啥区别)

如何解决Python 列表比 numpy 数组表现更好? Python 列表麻木

我最近报名参加了一门科学的 Python 课程,并且在课堂上展示了在某些情况下 numpy 数组如何比列表表现得更好。对于统计模拟,我尝试了两种方法,令人惊讶的是,numpy 数组需要更长的时间才能完成该过程。有人能帮我找出我的(可能的)错误吗?

我的第一个想法是代码的编写方式可能有问题,但我无法弄清楚它是如何出错的。该脚本会计算一个人平均需要多少次尝试才能完成一组已排序的贴纸:

Python 列表

我使用了一个函数,没有使用外部模块。

  1. import random as rd
  2. import statistics as st
  3. def collectStickers(experiments,collectible):
  4. obtained = []
  5. attempts = 0
  6. while(len(obtained) < collectible):
  7. new_sticker = rd.randint(1,collectible)
  8. if new_sticker not in obtained:
  9. obtained.append(new_sticker)
  10. attempts += 1
  11. experiments.append(attempts)
  12. experiments = []
  13. collectible = 20
  14. rep_experiment = 100000
  15. for i in range(1,rep_experiment):
  16. collectStickers(experiments,collectible)
  17. print(st.mean(experiments))

结果

对于像这样的简单实验来说,处理时间似乎还可以,但对于更复杂的目的,13.8 秒太多了。

  1. 72.06983069830699
  2. [Finished in 13.8s]

麻木

我无法使用任何函数,因为当我遵循与上述相同的逻辑时出现以下错误:

  • 运行时警告:空切片的平均值。

  • RuntimeWarning:在 double_scalars 中遇到无效值

所以我只是选择了天真的方式:

  1. import random as rd
  2. import numpy as np
  3. experiments = np.array([])
  4. rep_experiment = 100000
  5. for i in range(1,rep_experiment):
  6. obtained = np.array([])
  7. attempts = 0
  8. while(len(obtained) < 20):
  9. new_sticker = rd.randint(1,20)
  10. if new_sticker not in obtained:
  11. obtained = np.append(obtained,new_sticker)
  12. attempts += 1
  13. experiments = np.append(experiments,attempts)
  14. print(np.mean(experiments))

结果

几乎慢了 4 倍!

是函数使用的区别吗?

  1. 72.03112031120311
  2. [Finished in 54.2s]

解决方法

要真正考虑到 numpy 数组的强大功能,您需要以 numpy 的方式进行编程。 例如,尝试像这样对实验进行矢量化:

  1. def vectorized():
  2. rep_experiment = 100000
  3. collectible = 20
  4. # array of falses
  5. obtained = np.zeros(rep_experiment,dtype=bool)
  6. attempts = np.zeros(rep_experiment,dtype=int)
  7. targets = np.zeros((rep_experiment,collectible),dtype=bool)
  8. x = np.arange(0,100000,step=1,dtype=int)
  9. while False in targets:
  10. r = np.random.randint(0,collectible,size=rep_experiment)
  11. # add the new stickers to the collected target
  12. targets[x,r] = True
  13. # if collected all set obtained to True
  14. obtained[np.sum(targets,axis=1)==collectible] = True
  15. # increments the not obtained values
  16. attempts[~obtained] += 1
  17. print(attempts.mean(),attempts.std())

检查加速,对我来说大约是 50 X

,

np.append 在追加之前复制数组。

您的程序可能大部分时间都在做那些不必要的副本

  1. experiments = np.append(experiments,attempts)

编辑

正如预期的那样,用预定义的数组替换二次式 np.append() 使包装函数的速度大致相同。

用一套替换 obtained 贴纸列表可以让事情变得更快。

然而,瓶颈是缓慢的随机数生成器。运行 cProfile 显示 75% 的执行时间花费在 randint() 上。

结果见下面的代码(在我的机器上)。

  1. import random
  2. import statistics
  3. import timeit
  4. import numpy as np
  5. collectible = 20
  6. rep_experiment = 10000
  7. def original_collect_stickers():
  8. obtained = []
  9. attempts = 0
  10. while len(obtained) < collectible:
  11. new_sticker = random.randint(1,collectible)
  12. if new_sticker not in obtained:
  13. obtained.append(new_sticker)
  14. attempts += 1
  15. return attempts
  16. def set_collect_stickers():
  17. obtained = set()
  18. attempts = 0
  19. n = 0
  20. while n < collectible:
  21. new_sticker = random.randint(1,collectible)
  22. if new_sticker not in obtained:
  23. obtained.add(new_sticker)
  24. n += 1
  25. attempts += 1
  26. return attempts
  27. def repeat_with_list(fn):
  28. experiments = []
  29. for i in range(rep_experiment):
  30. experiments.append(fn())
  31. return statistics.mean(experiments)
  32. def repeat_with_numpy(fn):
  33. experiments = np.zeros(rep_experiment)
  34. for i in range(rep_experiment):
  35. experiments[i] = fn()
  36. return np.mean(experiments)
  37. def time_fn(name,fn,n=3):
  38. time_taken = timeit.timeit(fn,number=n) / n
  39. result = fn() # once more to get the result too
  40. print(f"{name:15}: {time_taken:.6f},result {result}")
  41. for wrapper in (repeat_with_list,repeat_with_numpy):
  42. for fn in (original_collect_stickers,set_collect_stickers):
  43. time_fn(f"{wrapper.__name__} {fn.__name__}",lambda: wrapper(fn))

结果是

  1. repeat_with_list original_collect_stickers: 0.747183,result 71.7912
  2. repeat_with_list set_collect_stickers: 0.688952,result 72.1002
  3. repeat_with_numpy original_collect_stickers: 0.752644,result 72.0978
  4. repeat_with_numpy set_collect_stickers: 0.685355,result 71.7515

编辑 2

使用 the fastrand library''s pcg32bounded() generator,即 new_sticker = fastrand.pcg32bounded(collectible) 使事情变得非常快:

  1. repeat_with_list original_collect_stickers: 0.761186,result 72.0185
  2. repeat_with_list set_collect_stickers: 0.690244,result 71.878
  3. repeat_with_list set_collect_stickers_fastrand: 0.116410,result 71.9323
  4. repeat_with_numpy original_collect_stickers: 0.759154,result 71.8604
  5. repeat_with_numpy set_collect_stickers: 0.696563,result 71.5482
  6. repeat_with_numpy set_collect_stickers_fastrand: 0.114212,result 71.6369

"import numpy as np" ImportError: No module named numpy

问题:没有安装 numpy

解决方法:

下载文件,安装

numpy-1.8.2-win32-superpack-python2.7

安装运行 import numpy,出现

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import numpy
  File "C:\Python27\lib\site-packages\numpy\__init__.py", line 153, in <module>
    from . import add_newdocs
  File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
    from .type_check import *
  File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
    import numpy.core.numeric as _nx
  File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 6, in <module>
    from . import multiarray
ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。

原因是:python 装的是 64 位的,numpy 装的是 32 位的

重新安装 numpy 为:numpy-1.8.0-win64-py2.7

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

目录

[TOC]

前言

具体我们来学 Numpy 的统计函数

(一)函数一览表

调用方式:np.*

.sum(a) 对数组 a 求和
.mean(a) 求数学期望
.average(a) 求平均值
.std(a) 求标准差
.var(a) 求方差
.ptp(a) 求极差
.median(a) 求中值,即中位数
.min(a) 求最大值
.max(a) 求最小值
.argmin(a) 求最小值的下标,都处里为一维的下标
.argmax(a) 求最大值的下标,都处里为一维的下标
.unravel_index(index, shape) g 根据 shape, 由一维的下标生成多维的下标

(二)统计函数 1

(1)说明

01.jpg

(2)输出

.sum(a)

01.png

.mean(a)

02.png

.average(a)

03.png

.std(a)

.var(a)

04.png

(三)统计函数 2

(1)说明

02.jpg

(2)输出

.max(a) .min(a)

.ptp(a)

.median(a)

05.png

.argmin(a)

.argmax(a)

.unravel_index(index,shape)

06.png

作者:Mark

日期:2019/02/11 周一

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

如何解决Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案?

希望有人能在这里提供帮助。我一直在绕圈子一段时间。我只是想设置一个 python 脚本,它将一些 json 数据从 REST API 加载到云数据库中。我在 Anaconda 上设置了一个虚拟环境(因为 GCP 库推荐这样做),安装了依赖项,现在我只是尝试导入库并向端点发送请求。 我使用 Conda(和 conda-forge)来设置环境并安装依赖项,所以希望一切都干净。我正在使用带有 Python 扩展的 VS 编辑器作为编辑器。 每当我尝试运行脚本时,我都会收到以下消息。我已经尝试了其他人在 Google/StackOverflow 上找到的所有解决方案,但没有一个有效。我通常使用 IDLE 或 Jupyter 进行脚本编写,没有任何问题,但我对 Anaconda、VS 或环境变量(似乎是相关的)没有太多经验。 在此先感谢您的帮助!

  \Traceback (most recent call last):
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 22,in <module>
from . import multiarray
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\multiarray.py",line 12,in <module>
from . import overrides
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\overrides.py",line 7,in <module>
from numpy.core._multiarray_umath import (
ImportError: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
File "c:\API\citi-bike.py",line 4,in <module>
import numpy as np
File "C:\Conda\envs\gcp\lib\site-packages\numpy\__init__.py",line 150,in <module>
from . import core
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 48,in <module>
raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions Failed. This error can happen for
many reasons,often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

* The Python version is: python3.9 from "C:\Conda\envs\gcp\python.exe"
* The NumPy version is: "1.21.1"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”

cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”

如何解决cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”?

我正在尝试升级一些软件包并为现有的 Python 程序整合我的 requirements.txt,以便将其移至 docker 容器。

这个容器将基于 tensorflow docker 容器,这决定了我必须使用的一些包版本。我们在 windows 下工作,我们希望能够在我们的机器上本地运行该程序(至少在一段时间内)。所以我需要找到一个适用于 docker 和 Windows 10 的配置。

Tensorflow 2.4.1 需要 numpy~=1.19.2。使用 numpy 1.20 时,pip 会抱怨 numpy 1.20 是一个不兼容的版本。

但是在使用 numpy~=1.19.2 时,导入 cvxpy 时出现以下错误。 pip 安装所有软件包都很好:

RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
Traceback (most recent call last):
  File "test.py",line 1,in <module>
    import cvxpy
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\__init__.py",line 18,in <module>
    from cvxpy.atoms import *
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\__init__.py",line 20,in <module>
    from cvxpy.atoms.geo_mean import geo_mean
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\geo_mean.py",in <module>
    from cvxpy.utilities.power_tools import (fracify,decompose,approx_error,lower_bound,File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\utilities\power_tools.py",in <module>
    from cvxpy.atoms.affine.reshape import reshape
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\reshape.py",in <module>
    from cvxpy.atoms.affine.hstack import hstack
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\hstack.py",in <module>
    from cvxpy.atoms.affine.affine_atom import AffAtom
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\atoms\affine\affine_atom.py",line 22,in <module>
    from cvxpy.cvxcore.python import canonInterface
  File "c:\Projekte\algo5\venv\lib\site-packages\cvxpy\cvxcore\python\__init__.py",line 3,in <module>
    import _cvxcore
ImportError: numpy.core.multiarray Failed to import

重现步骤:

1.) 在 Windows 10 下创建一个新的 Python 3.8 venv 并激活它

2.) 通过 requirements.txt 安装以下 pip install -r requirements.txt

cvxpy 
numpy~=1.19.2 # tensorflow 2.4.1 requires this version

3.) 通过 test.py

执行以下 python test.py
import cvxpy

if __name__ == ''__main__'':
    pass

如果我想使用 tensorflow 2.3,也会发生同样的事情。在这种情况下需要 numpy~=1.18,错误完全相同。

搜索错误发现很少的命中,可悲的是没有帮助我。

我该怎么做才能解决这个问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

关于Python 列表比 numpy 数组表现更好? Python 列表麻木python列表和数组有啥区别的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”的相关信息,请在本站寻找。

本文标签: