[python] SciPy와 NumPy의 관계

SciPy는 자체 네임 스페이스에서 NumPy의 기능 중 대부분 (1 개는 아님)을 제공하는 것으로 보입니다. 다시 말해,라는 이름의 함수가 있다면 numpy.foo거의 확실하게가 scipy.foo있습니다. 대부분의 경우 두 개는 정확히 같은 것으로 보이고 때로는 같은 함수 객체를 가리키는 경우도 있습니다.

때때로 그들은 다릅니다. 최근에 나온 예제를 제공하려면 :

  • numpy.log10부정적인 인수에 대해 NaN을 반환 하는 ufunc 입니다.
  • scipy.log10 음수 인수에 대한 복소수 값을 반환하며 ufunc가 아닌 것으로 보입니다.

동일한 약 말할 수 log, log2logn아니지만 대해 log1p[2].

반면에, numpy.expscipy.exp같은 ufunc 다른 이름이 될 것으로 보인다. 이것은 또한 사실이다 scipy.log1p하고 numpy.log1p.

또 다른 예는 numpy.linalg.solvevs scipy.linalg.solve입니다. 그것들은 비슷하지만 후자는 전자에 비해 몇 가지 추가 기능을 제공합니다.

왜 명백한 복제인가? 이것이 네임 스페이스 numpy로의 도매 수입 scipy일 경우, 왜 동작과 누락 된 기능의 미묘한 차이점이 있습니까? 혼란을 해결하는 데 도움이되는 중요한 논리가 있습니까?

[1] numpy.min, numpy.max, numpy.abs그리고 몇 가지 다른이의 더 대응이없는 scipy네임 스페이스를.

[2] NumPy 1.5.1 및 SciPy 0.9.0rc2를 사용하여 테스트했습니다.



답변

내가 마지막으로 확인했을 때, scipy __init__메소드는

from numpy import *

scipy 모듈을 가져올 때 전체 numpy 네임 스페이스가 scipy에 포함되도록합니다.

log10때문에 당신이 설명하는 동작은, 재미 버전이 NumPy와에서오고있다. 하나는 a ufunc이고 다른 하나는 numpy.lib함수입니다. scipy가 넘는 라이브러리 기능을 선호 왜 ufunc, 나는 내 머리 위로 떨어져 모른다.


편집 : 실제로, 나는 log10질문에 대답 할 수 있습니다 . scipy __init__방법을 보면 다음과 같습니다.

# Import numpy symbols to scipy name space
import numpy as _num
from numpy import oldnumeric
from numpy import *
from numpy.random import rand, randn
from numpy.fft import fft, ifft
from numpy.lib.scimath import *

log10당신이 scipy 얻을 기능에서 온다 numpy.lib.scimath. 그 코드를 보면 다음과 같습니다.

"""
Wrapper functions to more user-friendly calling of certain math functions
whose output data-type is different than the input data-type in certain
domains of the input.

For example, for functions like log() with branch cuts, the versions in this
module provide the mathematically valid answers in the complex plane:

>>> import math
>>> from numpy.lib import scimath
>>> scimath.log(-math.exp(1)) == (1+1j*math.pi)
True

Similarly, sqrt(), other base logarithms, power() and trig functions are
correctly handled.  See their respective docstrings for specific examples.
"""

그것은 그 모듈 오버레이를위한 기본 NumPy와의 ufuncs 보인다 sqrt, log, log2, logn, log10, power, arccos, arcsin,와 arctanh. 그것은 당신이보고있는 행동을 설명합니다. 그렇게 만들어진 기본 디자인 이유는 아마도 메일 링리스트 포스트에 묻혀있을 것입니다.


답변

SciPy 참조 안내서에서 :

… 모든 Numpy 함수는 scipy
네임 스페이스 에 포함되어 있으므로 Numpy를 추가로 가져 오지 않고도 해당 함수를 모두 사용할 수 있습니다.

의도는 사용자가 네임 스페이스 scipynumpy네임 스페이스 의 차이점을 알 필요는 없지만 분명히 예외를 발견 한 것입니다.


답변

SciPy FAQ 에서 NumPy의 일부 기능이 역사적인 이유로 여기에 있지만 SciPy에만 있어야하는 것으로 보입니다 .

NumPy와 SciPy의 차이점은 무엇입니까?

이상적인 세계에서 NumPy는 배열 데이터 유형과 색인, 정렬, 재구성, 기본 요소 별 함수 등과 같은 가장 기본적인 작업 만 포함합니다. 모든 숫자 코드는 SciPy에 있습니다. 그러나 NumPy의 중요한 목표 중 하나는 호환성입니다. 따라서 NumPy는 이전 버전 중 하나가 지원하는 모든 기능을 유지하려고합니다. 따라서 NumPy에는 선형 대수 함수가 포함되어 있지만 SciPy에 더 적합합니다. 어쨌든 SciPy에는 더 많은 기능을 갖춘 선형 대수 모듈 버전과 다른 많은 수치 알고리즘이 포함되어 있습니다. 파이썬으로 과학 컴퓨팅을 수행하는 경우 NumPy와 SciPy를 모두 설치해야합니다. 대부분의 새로운 기능은 NumPy가 아닌 SciPy에 속합니다.

이것은 왜 scipy.linalg.solve추가 기능을 제공 하는지 설명합니다 numpy.linalg.solve.

관련 질문에 대한 SethMMorton의 답변을 보지 못했습니다.


답변

SciPy 문서 소개 끝에 짧은 설명이 있습니다.

또 다른 유용한 명령은 source입니다. 파이썬으로 작성된 함수가 인수로 주어지면 해당 함수의 소스 코드 목록을 인쇄합니다. 이것은 알고리즘에 대해 배우거나 함수가 인수로 수행하는 작업을 정확하게 이해하는 데 도움이 될 수 있습니다. 또한 모듈 또는 패키지의 네임 스페이스를 보는 데 사용할 수있는 Python 명령 디렉토리를 잊지 마십시오.

나는 이것이 모든 관련 패키지에 대한 충분한 지식을 가진 사람이 일부 scipy와 numpy 함수 의 차이점을 정확하게 골라 낼 수 있다고 생각 합니다 (log10 질문에 전혀 도움이되지 않았습니다). 나는 확실히 그 지식을 가지고 source있지 않지만 그것을 나타내며 다른 방식으로 lapack scipy.linalg.solvenumpy.linalg.solve상호 작용합니다.

Python 2.4.3 (#1, May  5 2011, 18:44:23)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
>>> import scipy
>>> import scipy.linalg
>>> import numpy
>>> scipy.source(scipy.linalg.solve)
In file: /usr/lib64/python2.4/site-packages/scipy/linalg/basic.py

def solve(a, b, sym_pos=0, lower=0, overwrite_a=0, overwrite_b=0,
          debug = 0):
    """ solve(a, b, sym_pos=0, lower=0, overwrite_a=0, overwrite_b=0) -> x

    Solve a linear system of equations a * x = b for x.

    Inputs:

      a -- An N x N matrix.
      b -- An N x nrhs matrix or N vector.
      sym_pos -- Assume a is symmetric and positive definite.
      lower -- Assume a is lower triangular, otherwise upper one.
               Only used if sym_pos is true.
      overwrite_y - Discard data in y, where y is a or b.

    Outputs:

      x -- The solution to the system a * x = b
    """
    a1, b1 = map(asarray_chkfinite,(a,b))
    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
        raise ValueError, 'expected square matrix'
    if a1.shape[0] != b1.shape[0]:
        raise ValueError, 'incompatible dimensions'
    overwrite_a = overwrite_a or (a1 is not a and not hasattr(a,'__array__'))
    overwrite_b = overwrite_b or (b1 is not b and not hasattr(b,'__array__'))
    if debug:
        print 'solve:overwrite_a=',overwrite_a
        print 'solve:overwrite_b=',overwrite_b
    if sym_pos:
        posv, = get_lapack_funcs(('posv',),(a1,b1))
        c,x,info = posv(a1,b1,
                        lower = lower,
                        overwrite_a=overwrite_a,
                        overwrite_b=overwrite_b)
    else:
        gesv, = get_lapack_funcs(('gesv',),(a1,b1))
        lu,piv,x,info = gesv(a1,b1,
                             overwrite_a=overwrite_a,
                             overwrite_b=overwrite_b)

    if info==0:
        return x
    if info>0:
        raise LinAlgError, "singular matrix"
    raise ValueError,\
          'illegal value in %-th argument of internal gesv|posv'%(-info)

>>> scipy.source(numpy.linalg.solve)
In file: /usr/lib64/python2.4/site-packages/numpy/linalg/linalg.py

def solve(a, b):
    """
    Solve the equation ``a x = b`` for ``x``.

    Parameters
    ----------
    a : array_like, shape (M, M)
        Input equation coefficients.
    b : array_like, shape (M,)
        Equation target values.

    Returns
    -------
    x : array, shape (M,)

    Raises
    ------
    LinAlgError
        If `a` is singular or not square.

    Examples
    --------
    Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``:

    >>> a = np.array([[3,1], [1,2]])
    >>> b = np.array([9,8])
    >>> x = np.linalg.solve(a, b)
    >>> x
    array([ 2.,  3.])

    Check that the solution is correct:

    >>> (np.dot(a, x) == b).all()
    True

    """
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    one_eq = len(b.shape) == 1
    if one_eq:
        b = b[:, newaxis]
    _assertRank2(a, b)
    _assertSquareness(a)
    n_eq = a.shape[0]
    n_rhs = b.shape[1]
    if n_eq != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
#    lapack_routine = _findLapackRoutine('gesv', t)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgesv
    else:
        lapack_routine = lapack_lite.dgesv
    a, b = _fastCopyAndTranspose(t, a, b)
    pivots = zeros(n_eq, fortran_int)
    results = lapack_routine(n_eq, n_rhs, a, n_eq, pivots, b, n_eq, 0)
    if results['info'] > 0:
        raise LinAlgError, 'Singular matrix'
    if one_eq:
        return wrap(b.ravel().astype(result_t))
    else:
        return wrap(b.transpose().astype(result_t))

이것은 또한 첫 번째 게시물이므로 여기에서 무언가를 변경 해야하는 경우 알려주십시오.


답변

Wikipedia ( http://en.wikipedia.org/wiki/NumPy#History )에서 :

Numeric 코드는 Numarray의 새로운 기능을 구현할 수있을 정도로 유지 관리가 쉽고 유연하도록 조정되었습니다. 이 새로운 프로젝트는 SciPy의 일부였습니다. 배열 객체를 얻기 위해 전체 패키지를 설치하지 않으려면이 새로운 패키지를 분리하고 NumPy라고합니다.

scipy에 따라 numpy수입 많은 numpy편의를 위해 네임 스페이스로 기능합니다.


답변

linalg 패키지와 관련하여-scipy 함수는 많은 플랫폼에서 고도로 최적화 된 버전으로 제공되며 특히 상당히 밀도가 높은 매트릭스에서 작업 할 때 매우 우수한 성능을 제공하는 lapack 및 blas를 호출합니다. 반면에, 그들은 컴파일하기 쉬운 라이브러리가 아니기 때문에 포트란 컴파일러와 완전한 성능을 얻기 위해 많은 플랫폼 특정 조정이 필요합니다. 따라서, numpy는 많은 목적을 위해 충분히 유용한 많은 일반적인 선형 대수 함수의 간단한 구현을 제공합니다.


답변

정량 경제학 ‘ 강의

SciPy는 배열 데이터 유형 및 관련 기능을 사용하여 NumPy 위에 구축 된 다양한 도구를 포함하는 패키지입니다

실제로 SciPy를 가져올 때 SciPy 초기화 파일에서 볼 수 있듯이 NumPy도 얻습니다.

# Import numpy symbols to scipy name space
import numpy as _num
linalg = None
from numpy import *
from numpy.random import rand, randn
from numpy.fft import fft, ifft
from numpy.lib.scimath import *

__all__  = []
__all__ += _num.__all__
__all__ += ['randn', 'rand', 'fft', 'ifft']

del _num
# Remove the linalg imported from numpy so that the scipy.linalg package can be
# imported.
del linalg
__all__.remove('linalg')

그러나 NumPy 기능을 명시 적으로 사용하는 것이 더 일반적이고 더 나은 방법입니다.

import numpy as np

a = np.identity(3)

SciPy에서 유용한 것은 서브 패키지의 기능입니다

  • scipy.optimize, scipy.integrate, scipy.stats 등