source

SciPy와 NumPy의 관계

itover 2023. 2. 4. 08:24
반응형

SciPy와 NumPy의 관계

SciPy는 NumPy의 함수의 대부분을 (모든 [1] 함수는 아니지만) 자체 네임스페이스에서 제공하는 것으로 보입니다. ,이라는 이이라는 함수가 있습니다.numpy.foo , , , , , , 는 거의 확실히 scipy.foo대부분의 경우, 이 두 가지는 정확히 동일한 것으로 보이며, 종종 같은 함수 객체를 가리키기도 합니다.

가끔은 달라요최근에 나온 예를 들어 보겠습니다.

  • numpy.log10negative 인수에 대해 NaN을 반환하는 ufunc입니다.
  • scipy.log10부정 인수에 대한 복잡한 값을 반환하고 ufunc로 보이지 않습니다.

경우에도 수 있습니다.log,log2 ★★★★★★★★★★★★★★★★★」logn , , , , , , , , , , , , 에 대한 것이 .log1p2]

반,는numpy.exp ★★★★★★★★★★★★★★★★★」scipy.expufunc를 사용하다은 또한 .scipy.log1p ★★★★★★★★★★★★★★★★★」numpy.log1p.

다른 로는 '하다'가 있습니다.numpy.linalg.solve »scipy.linalg.solve비슷하지만 후자는 전자에 비해 몇 가지 추가 기능을 제공합니다.

왜복복 는??? 이것이 「 」의 하고 있는 는, 「 」numpyscipy네임스페이스, 왜 동작의 미묘한 차이와 누락된 기능일까요?혼란을 해소하는 데 도움이 되는 중요한 논리가 있습니까?

[1]numpy.min,numpy.max,numpy.abs은 대항할 만한 .scipy임스스네

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

했을 때 가 skipy, skipy.__init__는 amethod를합니다.

from numpy import *

따라서 scipy 모듈을 Import할 때 numpy 네임스페이스 전체가 scipy에 포함됩니다.

log10두 버전 모두 numpy에서 나왔기 때문에 흥미로운 동작입니다.하나는ufunc른른 , , , , , , , , , 。numpy.libscipy보다 라이브러리 선호하는 이유ufunc지금 당장은 모르겠어요.


EDIT: 사실, 제가 대답할 수 있는 것은log10 찌릿한 찌릿한 찌릿찌릿하다.__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 수 있는 는 skipy에서 수 .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.
"""

이 unpy ufuncs를 하고 있는 것 .sqrt,log,log2,logn,log10,power,arccos,arcsin , , , , 입니다.arctanh그러면 지금 보고 있는 동작이 설명됩니다.그렇게 하는 근본적인 디자인 이유는 아마도 메일링 리스트 포스트 어딘가에 묻혀 있을 것입니다.

SciPy 레퍼런스 가이드:

...에. pypy pypy pypy pypy pypy pypy pypy pypy pypy pypy 。scipyNumpy를 추가 Import하지 않고도 이러한 모든 기능을 사용할 수 있도록 네임스페이스를 만듭니다.

목적은 가 이 둘을 위한 입니다.scipy ★★★★★★★★★★★★★★★★★」numpy네임스페이스는 예외적인 걸 찾은 것 같은데

SciPy FAQ에 따르면 NumPy의 일부 함수는 과거의 이유로 SciPy에만 존재해야 하는 것으로 보입니다.

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

이상적인 환경에서 NumPy에는 어레이 데이터 타입과 가장 기본적인 조작(인덱스, 정렬, 재형성, 기본 요소별 함수 등)만 포함됩니다.모든 숫자 코드는 SciPy에 있습니다.그러나 NumPy의 중요한 목표 중 하나는 호환성이기 때문에 NumPy는 이전 제품 중 하나에서 지원되는 모든 기능을 유지하려고 합니다.따라서 NumPy는 SciPy에 더 적절하게 속함에도 불구하고 일부 선형 대수 함수를 포함한다.어떤 경우에도 SciPy는 선형 대수 모듈의 보다 완전한 기능을 갖춘 버전과 많은 다른 수치 알고리즘을 포함합니다.파이썬으로 과학적 컴퓨팅을 하고 있다면 NumPy와 SciPy를 모두 설치해야 합니다.대부분의 새로운 기능은 NumPy가 아닌 SciPy에 속합니다.

알 수 있다.scipy.linalg.solve에서는 보 offers보다 보 over보다 더 합니다.numpy.linalg.solve.

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

SciPy 설명서의 마지막에 다음과 같은 짧은 코멘트가 있습니다.

하나의 는 '하다'입니다.sourcePython으로 작성된 함수를 인수로 지정하면 해당 함수의 소스 코드 목록이 출력됩니다.이것은 알고리즘에 대해 학습하거나 함수가 인수로 무엇을 하고 있는지를 정확하게 이해하는 데 도움이 됩니다.또한 모듈 또는 패키지의 네임스페이스를 확인하는 데 사용할 수 있는 Python 명령어 dir도 잊지 마십시오.

이것에 의해, 관련된 모든 패키지에 대해 충분한 지식을 가지는 사람이, 몇개의 scify 함수와 numpy 함수의 차이를 정확하게 판단할 수 있다고 생각합니다(log10 질문에는 전혀 도움이 되지 않았습니다).저는 그런 지식은 전혀 없지만source는, 을 있습니다.scipy.linalg.solve ★★★★★★★★★★★★★★★★★」numpy.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 )에서 :

숫자 코드는 Numarray의 새로운 기능을 구현하기에 충분할 정도로 유지보수가 용이하고 유연하도록 수정되었습니다.이 새로운 프로젝트는 SciPy의 일부였다.어레이 오브젝트를 취득하기 위해서만 패키지 전체를 인스톨 하는 것을 피하기 위해서, 이 새로운 패키지는 분리되어 NumPy라고 불리고 있습니다.

scipy 의존하다numpy 수입하다numpy네임스페이스로 기능합니다.

linalg 패키지에 대해서 - 스키피 함수는 lapack과 blas를 호출합니다.이러한 함수는 많은 플랫폼에서 매우 최적화된 버전으로 사용할 수 있으며, 특히 상당히 고밀도 매트릭스에서의 연산에 매우 뛰어난 성능을 제공합니다.한편, 컴파일 하기 쉬운 라이브러리는 아니기 때문에, 풀 퍼포먼스를 얻기 위해서는 Fortran 컴파일러와 많은 플랫폼 고유의 조정이 필요합니다.따라서, numpy는 많은 공통 선형 대수 함수의 간단한 구현을 제공하며, 이는 종종 많은 목적을 위해 충분히 좋다.

'양적 경제' 강의에서

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

실제로 SciPy를 Import할 때 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에서 유용한 것은 하위 패키지의 기능이다.

  • 삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐삐.integrate, scipy.disples 등

복제가 주로 하위 호환성을 위한 것임을 설명하는 SciPy FAQ에 더하여 NumPy 문서에서 다음과 같이 더 명확하게 설명됩니다.

옵션으로 SciPy 가속 루틴(numpy.dual)

Scipy에 의해 가속될 수 있는 함수의 별칭.

SciPy는 FFT, 선형 대수 및 특수 함수를 위해 가속되거나 개선된 라이브러리를 사용하도록 구축될 수 있습니다.SciPy를 사용할 수 있을 때 개발자는 이러한 가속화된 기능을 투명하게 지원할 수 있지만 NumPy만 설치한 사용자를 지원할 수 있습니다.

간결하게 하기 위해 다음과 같이 합니다.

  • 선형 대수
  • FFT
  • 첫 번째 종류의 수정된 베셀 함수, 순서 0

또한 SciPy 튜토리얼에서 다음을 수행합니다.

SciPy의 최상위 레벨에는 NumPy 및 numpy.lib.scimath의 기능도 포함되어 있습니다.단, NumPy 모듈에서 직접 사용하는 것이 좋습니다.

따라서 새로운 애플리케이션의 경우 SciPy의 최상위 레벨에서 중복되는 어레이 작업의 NumPy 버전을 선호해야 합니다.위에 나열된 도메인에서는 SciPy에 있는 도메인을 선호하고 필요에 따라 NumPy에 있는 이전 버전과의 호환성을 확인해야 합니다.

으로 볼 때, NumPy의 합니다(NumPy의 경우는 ).random그러나 SciPy의 서브패키지에 도메인 고유의 루틴이 모두 존재하기 때문에 SciPy의 최상위 레벨은 거의 사용하지 않습니다.

언급URL : https://stackoverflow.com/questions/6200910/relationship-between-scipy-and-numpy

반응형