mic*_*ard 3 python interpolation numpy scipy
我理解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)
Run Code Online (Sandbox Code Playgroud)
输出:
array(7.749999999999992)
type is <class 'numpy.ndarray'>
shape is ()
ndim is 0
7.749999999999992
Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清,我不希望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
Run Code Online (Sandbox Code Playgroud)
所述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)
Run Code Online (Sandbox Code Playgroud)
许多numpy操作确实返回标量而不是0d数组.
In [330]: np.arange(3).sum()
Out[330]: 3
Run Code Online (Sandbox Code Playgroud)
虽然实际上它返回一个numpy对象
In [341]: type(np.arange(3).sum())
Out[341]: numpy.int32
Run Code Online (Sandbox Code Playgroud)
它有一个形状()和ndim 0.
而interp1d返回一个数组.
In [344]: type(f(2.5))
Out[344]: numpy.ndarray
Run Code Online (Sandbox Code Playgroud)
您可以使用[()]索引来提取值
In [345]: f(2.5)[()]
Out[345]: 7.75
In [346]: type(f(2.5)[()])
Out[346]: numpy.float64
Run Code Online (Sandbox Code Playgroud)
这可能只是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.
Run Code Online (Sandbox Code Playgroud)
===============
问题的另一面是为什么numpy甚至有一个0d数组.链接的答案可能就足够了.但是,习惯于MATLAB的人经常会问这个问题.在MATLAB中,几乎所有东西都是2d.没有任何(真正的)标量.现在,MATLAB具有结构和单元格,以及具有2个以上维度的矩阵.但我记得有一段时间(在20世纪90年代)没有这些时间.一切,字面上,是一个二维矩阵.
的np.matrix近似于MATLAB情况下,在2D固定其阵列.但它确实有一种_collapse可以返回'标量'的方法.
| 归档时间: |
|
| 查看次数: |
1006 次 |
| 最近记录: |