【问题标题】:Scipy interpolate returns a 'dimensionless' arrayScipy interpolate 返回一个“无量纲”数组
【发布时间】:2016-10-02 05:41:27
【问题描述】:

我知道interp1d 期望插入一个值数组,但是将浮点数传递给它时的行为很奇怪,以至于询问发生了什么以及返回的究竟是什么

import numpy as np
from scipy.interpolate import interp1d

x = np.array([1,2,3,4])
y = np.array([5,7,9,15])
f = interp1d(x,y, kind='cubic')
a = f(2.5)

print(repr(a))
print("type is {}".format(type(a)))
print("shape is {}".format(a.shape))
print("ndim is {}".format(a.ndim))
print(a)

输出:

array(7.749999999999992)
type is <class 'numpy.ndarray'>
shape is ()
ndim is 0
7.749999999999992

编辑:澄清一下,我不希望 numpy 甚至有一个无量纲、无形的数组,更不用说 scipy 函数返回一个。

print("Numpy version is {}".format(np.__version__))
print("Scipy version is {}".format(scipy.__version__))

Numpy version is 1.10.4
Scipy version is 0.17.0

【问题讨论】:

  • 我可以复制这个。你能具体说明你的问题是什么吗?我猜你希望它应该返回一个 float 并且你在问这是否是一个错误。
  • 这个相关问题可能有助于澄清事情:stackoverflow.com/questions/773030/…
  • 鉴于 f(2) = 7 和 f(3) = 9,我认为 2.5 的插值介于 7 和 9 之间并不奇怪。
  • @Forzaa- 问题不在于插值,而是返回的无量纲、无形数组。我同意这个值本身是正确的。
  • @RyanJ.Smith 这完全清楚了。谢谢。

标签: python numpy scipy interpolation


【解决方案1】:

interp1d 返回一个与输入形状相匹配的值 - 如果需要,在包装 np.array() 之后:

In [324]: f([1,2,3])
Out[324]: array([ 5.,  7.,  9.])

In [325]: f([2.5])
Out[325]: array([ 7.75])

In [326]: f(2.5)
Out[326]: array(7.75)

In [327]: f(np.array(2.5))
Out[327]: array(7.75)

许多 numpy 操作确实返回标量而不是 0d 数组。

In [330]: np.arange(3).sum()
Out[330]: 3

虽然实际上它返回一个 numpy 对象

In [341]: type(np.arange(3).sum())
Out[341]: numpy.int32

确实有一个形状 () 和 ndim 0

interp1d 返回一个数组。

In [344]: type(f(2.5))
Out[344]: numpy.ndarray

您可以使用[()] 索引提取值

In [345]: f(2.5)[()]
Out[345]: 7.75

In [346]: type(f(2.5)[()])
Out[346]: numpy.float64

这可能只是scipy 代码中的疏忽。人们希望在某一点上多久进行一次插值?在规则的点网格上插值不是更常见吗?

===================

f.__call__ 的文档对返回数组非常明确。

Evaluate the interpolant

Parameters
----------
x : array_like
    Points to evaluate the interpolant at.

Returns
-------
y : array_like
    Interpolated values. Shape is determined by replacing
    the interpolation axis in the original array with the shape of x.

================

问题的另一面是为什么numpy 甚至有一个 0d 数组。链接的答案可能就足够了。但是习惯了 MATLAB 的人经常会问这个问题。在 MATLAB 中,几乎所有东西都是二维的。没有任何(真正的)标量。现在 MATLAB 有结构和单元,以及超过 2 维的矩阵。但我记得有一段时间(在 1990 年代)它没有这些。一切,字面意思,都是一个二维矩阵。

np.matrix 近似于 MATLAB 的情况,将其数组固定为 2d。但它确实有一个可以返回“标量”的_collapse 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-04-02
    相关资源
    最近更新 更多