通过Python中的OpenTURNS将1D数组转换为示例

2024-10-01 13:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试通过克里格法在二维网格上插值响应,如下示例: How to interpolate 2D spatial data with kriging in Python?

但是,当我试图在OpenTURNS中从1D数组创建样本时

import numpy as np
import openturns as ot
observations = ot.Sample(np.array([1,2,3]))

我一直在犯这个错误

TypeError: Wrong number or type of arguments for overloaded function 'new_Sample'.
  Possible C/C++ prototypes are:
    OT::Sample::Sample()
    OT::Sample::Sample(OT::UnsignedInteger const,OT::UnsignedInteger const)
    OT::Sample::Sample(OT::UnsignedInteger const,OT::Point const &)
    OT::Sample::Sample(OT::Sample const &,OT::UnsignedInteger const,OT::UnsignedInteger const)
    OT::Sample::Sample(OT::SampleImplementation const &)
    OT::Sample::Sample(OT::Sample const &)
    OT::Sample::Sample(PyObject *)

这也不起作用:

observations = ot.Sample(np.array([[1],[2],[3]]))

Tags: sampleimport网格示例asnpotarray
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:11

例外情况是因为这是一种模棱两可的情况。array包含3个值:Sample类不知道此数据是对应于维度1中由3个点组成的样本,还是对应于维度3中有一个点的样本

阐明这一点的类别有:

  • {}类管理一个多维实向量-它有一个维度(组件的数量)
  • {}管理点的集合-它有一个大小(样本中的点的数量)和一个维度(样本中每个点的维度)

Python数据类型和OpenTURNS数据类型之间有自动转换:

  • Pythonlisttuple或1D numpyarray会自动转换为ot.Point()
  • Pythonlist列表或2D numpyarray会自动转换为ot.Sample()

创建一维Sample的常用方法是从浮点数列表中创建。 请让我举例说明这三种结构

(案例1)要从1D数组创建点,只需将其传递给Point类:

import numpy as np
import openturns as ot

array_1D = np.array([1.0, 2.0, 3.0])
point = ot.Point(array_1D)
print(point)

这将打印[1,2,3],即维度3中的一个点

(案例2)为了从2D数组创建Sample,我们添加了所需的方括号

array_2D = np.array([[1.0], [2.0], [3.0]])
sample = ot.Sample(array_2D)
print(sample)

这张照片是:

0 : [ 1 ]
1 : [ 2 ]
2 : [ 3 ]

这是一个由3个点组成的样本;每个点都有一个维度

(案例3)我们经常需要从浮动列表中创建一个Sample。这可以通过列表理解更容易地完成

list_of_floats = [1.0, 2.0, 3.0]
sample = ot.Sample([[v] for v in list_of_floats])
print(sample)

这将打印与上一示例中相同的样本。 最后一个脚本:

observations = ot.Sample(np.array([[1],[2],[3]]))  
# Oups: should use 1.0 instead of 1

在我的机器上很好用。请注意,OpenTURNS只管理浮点值的点,而不管理int类型的点。这就是为什么我写:

observations = ot.Sample(np.array([[1.0], [2.0], [3.0]]))  

让这一切变得足够清楚。 但是,对array函数的调用是不必要的。使用起来更简单:

observations = ot.Sample([[1.0], [2.0], [3.0]])  

相关问题 更多 >