GVKun编程网logo

为什么 unittest 不将 numpy 数组视为序列?(为什么numpy不能用)

3

在本文中,我们将给您介绍关于为什么unittest不将numpy数组视为序列?的详细内容,并且为您解答为什么numpy不能用的相关问题,此外,我们还将为您提供关于AnacondaNumpy错误“Imp

在本文中,我们将给您介绍关于为什么 unittest 不将 numpy 数组视为序列?的详细内容,并且为您解答为什么numpy不能用的相关问题,此外,我们还将为您提供关于Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”、Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy 协方差矩阵 numpy.cov的知识。

本文目录一览:

为什么 unittest 不将 numpy 数组视为序列?(为什么numpy不能用)

为什么 unittest 不将 numpy 数组视为序列?(为什么numpy不能用)

Numpy 数组与 Python 序列具有不同的相等语义;在 Numpy 中,相等是按元素计算的。例如:

>>> [1,2,3] == [1,3]
True

>>> np.array([1,3]) == [1,3]
array([ True,True,True])

这打破了 assertSequenceEqual 所做的假设,导致测试失败。

为了测试 numpy 数组的相等性,您应该更喜欢 numpy.testing.assert_array_equal 之类的实用程序:

>>> np.testing.assert_array_equal(np.array([1,3]),[1,3])
,

我可能对这个问题给予了更多的关注,但我很好奇断言是如何工作的。

(从另一个内置包的开发工作中,argparse 我知道文档从来都不是准确的。文档中无法捕获代码的细微差别。文档必须平衡对大多数用户的有用性,与更挑剔的用户的期望背道而驰。)

这是该方法的完整代码:

Signature: M.assertSequenceEqual(seq1,seq2,msg=None,seq_type=None)
Source:   
    def assertSequenceEqual(self,seq1,seq_type=None):
        """An equality assertion for ordered sequences (like lists and tuples).

        For the purposes of this function,a valid ordered sequence type is one
        which can be indexed,has a length,and has an equality operator.

        Args:
            seq1: The first sequence to compare.
            seq2: The second sequence to compare.
            seq_type: The expected datatype of the sequences,or None if no
                    datatype should be enforced.
            msg: Optional message to use on failure instead of a list of
                    differences.

对于此函数而言,有效的有序序列类型是 它可以被索引,有长度,并且有一个相等运算符。

ndarray 有一个相等运算符,但 numpy 不允许在 if 语句中使用它。

        """
        if seq_type is not None:
            seq_type_name = seq_type.__name__
            if not isinstance(seq1,seq_type):
                raise self.failureException('First sequence is not a %s: %s'
                                        % (seq_type_name,safe_repr(seq1)))
            if not isinstance(seq2,seq_type):
                raise self.failureException('Second sequence is not a %s: %s'
                                        % (seq_type_name,safe_repr(seq2)))
        else:
            seq_type_name = "sequence"

        differing = None
        try:
            len1 = len(seq1)
        except (TypeError,NotImplementedError):
            differing = 'First %s has no length.    Non-sequence?' % (
                    seq_type_name)

        if differing is None:
            if seq1 == seq2:
                return

这是 numpy 抛出错误的步骤。对于像 liststring 这样的内置序列类型,这是一个非常好的表达式。我想他们可以将它包装在 try/except ValueError 中。但是是由核心 python 来预测外部库失败的所有方式,还是库本身应该注意提供自己有用的测试?

其余代码尝试确定序列的不同之处,无论是长度还是元素值。

            differing = '%ss differ: %s != %s\n' % (
                    (seq_type_name.capitalize(),) +
                    _common_shorten_repr(seq1,seq2))

            for i in range(min(len1,len2)):
                try:
                    item1 = seq1[i]
                except (TypeError,IndexError,NotImplementedError):
                    differing += ('\nUnable to index element %d of first %s\n' %
                                 (i,seq_type_name))
                    break

                try:
                    item2 = seq2[i]
                except (TypeError,NotImplementedError):
                    differing += ('\nUnable to index element %d of second %s\n' %
                                 (i,seq_type_name))
                    break

                if item1 != item2:
                    differing += ('\nFirst differing element %d:\n%s\n%s\n' %
                                 ((i,) + _common_shorten_repr(item1,item2)))
                    break
            else:
                if (len1 == len2 and seq_type is None and
                    type(seq1) != type(seq2)):
                    # The sequences are the same,but have differing types.
                    return

            if len1 > len2:
                differing += ('\nFirst %s contains %d additional '
                             'elements.\n' % (seq_type_name,len1 - len2))
                try:
                    differing += ('First extra element %d:\n%s\n' %
                                  (len2,safe_repr(seq1[len2])))
                except (TypeError,NotImplementedError):
                    differing += ('Unable to index element %d '
                                  'of first %s\n' % (len2,seq_type_name))
            elif len1 < len2:
                differing += ('\nSecond %s contains %d additional '
                             'elements.\n' % (seq_type_name,len2 - len1))
                try:
                    differing += ('First extra element %d:\n%s\n' %
                                  (len1,safe_repr(seq2[len1])))
                except (TypeError,NotImplementedError):
                    differing += ('Unable to index element %d '
                                  'of second %s\n' % (len1,seq_type_name))
        standardMsg = differing
        diffMsg = '\n' + '\n'.join(
            difflib.ndiff(pprint.pformat(seq1).splitlines(),pprint.pformat(seq2).splitlines()))

        standardMsg = self._truncateMessage(standardMsg,diffMsg)
        msg = self._formatMessage(msg,standardMsg)
        self.fail(msg)
File:      /usr/lib/python3.8/unittest/case.py

差异诊断旨在处理列表等序列,具有 len 的对象和元素明智的迭代是有意义的。

带有列表的示例:

In [309]: M.assertSequenceEqual([1,3],[1.,2.,3.])
In [310]: M.assertSequenceEqual([1,4])
Traceback (most recent call last):
  File "<ipython-input-310-3cc2193995b9>",line 1,in <module>
    M.assertSequenceEqual([1,4])
  File "/usr/lib/python3.8/unittest/case.py",line 1100,in assertSequenceEqual
    self.fail(msg)
  File "/usr/lib/python3.8/unittest/case.py",line 753,in fail
    raise self.failureException(msg)
AssertionError: Sequences differ: [1,3] != [1.0,2.0,4]

First differing element 2:
3
4

- [1,3]
+ [1.0,4]

In [311]: M.assertSequenceEqual([1,3,0],4])
Traceback (most recent call last):
  File "<ipython-input-311-1a7c548c65ee>",0] != [1.0,4]

First differing element 2:
3
4

First sequence contains 1 additional elements.
First extra element 3:
0

- [1,0]
+ [1.0,4]

对于列表中的列表:

In [314]: M.assertSequenceEqual([[1,3]],[[1,4]])
Traceback (most recent call last):
  File "<ipython-input-314-e71a55865cae>",in <module>
    M.assertSequenceEqual([[1,4]])
  File "/usr/lib/python3.8/unittest/case.py",in fail
    raise self.failureException(msg)
AssertionError: Sequences differ: [[1,3]] != [[1,4]]

First differing element 0:
[1,3]
[1,4]

- [[1,3]]
?         ^

+ [[1,4]]
?         ^

在不深入细节的情况下,目前尚不清楚诊断步骤是否会更好地处理 numpy 数组。数组的 len 只是第一维的大小。

将其与 numpy 自己的测试人员报告的错误进行对比。当 unittest 提供更适合多维数组的测试器时,为什么要强制 numpy 使用数组?

In [319]: numpy.testing.assert_array_almost_equal([[1,4]])
Traceback (most recent call last):
  File "<ipython-input-319-9392a2140ddd>",in <module>
    numpy.testing.assert_array_almost_equal([[1,4]])
  File "/usr/local/lib/python3.8/dist-packages/numpy/testing/_private/utils.py",line 1042,in assert_array_almost_equal
    assert_array_compare(compare,x,y,err_msg=err_msg,verbose=verbose,File "/usr/local/lib/python3.8/dist-packages/numpy/testing/_private/utils.py",line 840,in assert_array_compare
    raise AssertionError(msg)
AssertionError: 
Arrays are not almost equal to 6 decimals

Mismatched elements: 1 / 3 (33.3%)
Max absolute difference: 1
Max relative difference: 0.25
 x: array([[1,3]])
 y: array([[1,4]])

虽然测试阵列可能很小,但生产阵列通常非常大。这种统计报告风格比 unittest 方法更详细的差异更有用。

注意 numpy 测试做了什么。我给了它列表,它转换为 numpy 数组。这是 numpy 中的常见做法。在开始时编写将输入转换为“标准”类型的代码要简单得多,而不是试图在整个代码中考虑不同的行为。就其价值而言,numpy 有一个非常好的 tolist 方法

In [322]: M.assertSequenceEqual([1,np.array([1.,3.]).tolist())
,

你忘记展示失败了!

In [1]: import unittest
   ...: unittest.TestCase().assertSequenceEqual([1,3.]))
Traceback (most recent call last):
  File "<ipython-input-1-fb3ef7cd88ef>",line 2,in <module>
    unittest.TestCase().assertSequenceEqual([1,3.]))
  File "/usr/lib/python3.8/unittest/case.py",line 1043,in assertSequenceEqual
    if seq1 == seq2:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

该方法使用 if seq1 == seq2:。对于 seq1 == seq2 结果是布尔数组,它没有特殊情况。这是一个简单的 if 语句。当在 Python 上下文中使用需要标量布尔值(例如 numpy)的数组(具有多个元素)时,if 会引发 ValueError。

numpy 有自己的测试工具,例如 https://numpy.org/doc/stable/reference/generated/numpy.testing.assert_array_equal.html

您的第一个数组是整数 dtype,第二个是浮点数。它们应该相等还是不相等?为什么?我们建议对浮动进行 allclose 测试。

单元素数组

In [46]: unittest.TestCase().assertSequenceEqual([1],np.array([1.]))
In [47]: unittest.TestCase().assertSequenceEqual([1],np.array([3.]))
Traceback (most recent call last):
  File "<ipython-input-47-049a26b28f34>",in <module>
    unittest.TestCase().assertSequenceEqual([1],np.array([3.]))
  File "/usr/lib/python3.8/unittest/case.py",in fail
    raise self.failureException(msg)
AssertionError: Sequences differ: [1] != array([3.])

First differing element 0:
1
3.0

- [1]
+ array([3.])
,

numpy 提供 numpy.testing.assert_array_almost_equal 和其他测试方法,用于 unittest(和其他测试框架)。 pandas 提供 pandas.testing.assert_series_equal 等。

因此,实现标准库支持的是第三方库,而不是相反。

,

assertSequenceEqual(first,second,seq_type=None)¶ 两个序列相等。如果提供了 seq_type,则首先 第二个必须是 seq_type 的实例,否则将引发故障。 如果序列不同,则构建错误消息 显示了两者之间的差异。这个方法不叫 直接通过 assertEqual() 实现,但用于实现 assertListEqual() 和 assertTupleEqual()。

还有 numpy 函数。

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 (将#修改为@)

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

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

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

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

numpy 协方差矩阵 numpy.cov

numpy 协方差矩阵 numpy.cov

numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)[source]

Estimate a covariance matrix, given data and weights.

Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, X = [x_1, x_2, ... x_N]^T, then the covariance matrix element C_{ij} is the covariance of x_i and x_j. The element C_{ii} is the variance of x_i.

See the notes for an outline of the algorithm.

Parameters:

m : array_like

A 1-D or 2-D array containing multiple variables and observations. Each row (行) of m represents a variable(变量), and each column(列) a single observation of all those variables(样本). Also see rowvar below.

y : array_like, optional

An additional set of variables and observations. y has the same form as that of m.

rowvar : bool, optional

If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

bias : bool, optional

Default normalization (False) is by (N 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5.

ddof : int, optional

If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None.

New in version 1.5.

fweights : array_like, int, optional

1-D array of integer freguency weights; the number of times each observation vector should be repeated.

New in version 1.10.

aweights : array_like, optional

1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors.

New in version 1.10.

Returns:

out : ndarray

The covariance matrix of the variables.

See also

corrcoef
Normalized covariance matrix

Notes

Assume that the observations are in the columns of the observation array m and let fweights and aweights for brevity. The steps to compute the weighted covariance are as follows:

>>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=1, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2) 

Note that when == 1, the normalization factor v1 (v1**2 ddof v2) goes over to (np.sum(f) ddof) as it should.

Examples

Consider two variables, x_0 and x_1, which correlate perfectly, but in opposite directions:

>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2],  [2, 1, 0]]) 

Note how x_0 increases while x_1 decreases. The covariance matrix shows this clearly:

>>> np.cov(x) array([[ 1., -1.],  [-1., 1.]]) 

Note that element C_{0,1}, which shows the correlation between x_0 and x_1, is negative.

Further, note how x and y are combined:

>>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.stack((x, y), axis=0) >>> print(np.cov(X)) [[ 11.71 -4.286 ]  [ -4.286 2.14413333]] >>> print(np.cov(x, y)) [[ 11.71 -4.286 ]  [ -4.286 2.14413333]] >>> print(np.cov(x)) 11.71

总结


理解协方差矩阵的关键就在于牢记它的计算是不同维度之间的协方差,而不是不同样本之间。拿到一个样本矩阵,最先要明确的就是一行是一个样本还是一个维度,心中明确整个计算过程就会顺流而下,这么一来就不会迷茫了。

今天关于为什么 unittest 不将 numpy 数组视为序列?为什么numpy不能用的分享就到这里,希望大家有所收获,若想了解更多关于Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、cvxpy 和 numpy 之间的版本冲突:“针对 API 版本 0xe 编译的模块,但此版本的 numpy 是 0xd”、Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy 协方差矩阵 numpy.cov等相关知识,可以在本站进行查询。

本文标签: