【问题标题】:How to create an array containing only inf with a specific shape?如何创建一个仅包含具有特定形状的 inf 的数组?
【发布时间】:2019-12-06 06:55:10
【问题描述】:

这是一个 Matlab 向量:a = [inf(m,1);ones(m,1)]

我尝试用 python 方式创建一个类似的对象。

我试过这个:

import numpy as np

a = np.stack((np.tile(np.array([np.inf]), (m, 0))),np.ones((m,0)))

例如,通过在控制台中将 m 更改为 5 并尝试使用 PyCharm 查看它,我收到了以下消息:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pydev\_pydev_comm\server.py", line 34, in handle
    self.processor.process(iprot, oprot)
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 266, in process
    self.handle_exception(e, result)
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 254, in handle_exception
    raise e
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 263, in process
    result.success = call()
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 228, in call
    return f(*(args.__dict__[k] for k in api_args))
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pydev\_pydev_bundle\pydev_console_utils.py", line 359, in getArray
    return pydevd_thrift.table_like_struct_to_thrift_struct(array, name, roffset, coffset, rows, cols, format)
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pydev\_pydevd_bundle\pydevd_thrift.py", line 602, in table_like_struct_to_thrift_struct
    return TYPE_TO_THRIFT_STRUCT_CONVERTERS[type_name](array, name, roffset, coffset, rows, cols, format)
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pydev\_pydevd_bundle\pydevd_thrift.py", line 377, in array_to_thrift_struct
    array, array_chunk, r, c, f = array_to_meta_thrift_struct(array, name, format)
  File "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pydev\_pydevd_bundle\pydevd_thrift.py", line 476, in array_to_meta_thrift_struct
    bounds = (array.min(), array.max())
  File "C:\Users\Azerty\PycharmProjects\OptionsHedgeFund\venv37\lib\site-packages\numpy\core\_methods.py", line 32, in _amin
    return umr_minimum(a, axis, None, out, keepdims, initial)
ValueError: zero-size array to reduction operation minimum which has no identity

这有什么问题?

【问题讨论】:

  • 对于不熟悉 matlab 的人......a = [inf(m,1);ones(m,1)] 是做什么的?
  • 我们如何在 Matlab 中创建矩阵,总是在括号 [x,y,z;a,b,c] 之间并指定我们使用的行 ; 这将在 Python 中返回:([x,y,z]n\ [a,b,c])
  • 那么您是否要创建一个 m x 2 矩阵,其第一行由无穷大组成,第二行由一个组成?
  • 您可能想用 1 替换零,并将右括号移到最右边并使用 concatenate 而不是 stack
  • 我的错,我想我弄错了..我现在确定 matlab 代码生成 m 行 inf,然后从 inf 行的最后一行开始添加,m 行一个

标签: python-3.x matlab numpy


【解决方案1】:

Numpy 有专门用于填充数组的函数。请参阅“完整()”,“填充()”。

a = np.full((2, 2), np.inf)
array([[inf, inf],
       [inf, inf]])

【讨论】:

    【解决方案2】:

    在 Octave 会话中:

    >> m = 5;
    >> a = [inf(m,1); ones(m,1)];
    >> size(a)
    ans =
    
       10    1
    
    >> a
    a =
    
       Inf
       Inf
       Inf
       Inf
       Inf
         1
         1
         1
         1
         1
    

    ipython 会话中:

    In [21]: m=5                                                                                                 
    In [22]: np.vstack([np.ones((m,1))*np.inf, np.ones((m,1))])                                                  
    Out[22]: 
    array([[inf],
           [inf],
           [inf],
           [inf],
           [inf],
           [ 1.],
           [ 1.],
           [ 1.],
           [ 1.],
           [ 1.]])
    In [23]: _.shape                                                                                             
    Out[23]: (10, 1)
    

    做同样事情的变体:`

    np.concatenate([np.full((m,1), np.inf), np.ones((m,1))], axis=0)
    

    ===

    对于两行,从 (1,m) 形状开始:

    >> a = [inf(1,m); ones(1,m)];
    >> size(a)
    ans =
    
       2   5
    
    >> a
    a =
    
       Inf   Inf   Inf   Inf   Inf
         1     1     1     1     1
    
    In [26]: np.concatenate([np.full((1,m), np.inf), np.ones((1,m))], axis=0)                                    
    Out[26]: 
    array([[inf, inf, inf, inf, inf],
           [ 1.,  1.,  1.,  1.,  1.]])
    

    ===

    至于您的错误,np.stack 在连接两个 (5,0) 形状的阵列时遇到问题(我不完全确定原因)。

    In [27]: a = np.stack((np.tile(np.array([np.inf]), (m, 0))),np.ones((m,0)))                                  
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-27-c6f8ec8462c9> in <module>
    ----> 1 a = np.stack((np.tile(np.array([np.inf]), (m, 0))),np.ones((m,0)))
    
    /usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in stack(arrays, axis, out)
        417 
        418     result_ndim = arrays[0].ndim + 1
    --> 419     axis = normalize_axis_index(axis, result_ndim)
        420 
        421     sl = (slice(None),) * axis + (_nx.newaxis,)
    
    TypeError: only size-1 arrays can be converted to Python scalars
    

    你的错误是不同的;看起来它是由pydev 生成的,而不是 Python 本身。

    但是检查一下:

    In [28]: np.tile(np.array([np.inf]), (m, 0))                                                                 
    Out[28]: array([], shape=(5, 0), dtype=float64)
    In [29]: np.ones((m,0))                                                                                      
    Out[29]: array([], shape=(5, 0), dtype=float64)
    
    In [31]: a = np.vstack([(np.tile(np.array([np.inf]), (m, 0))),np.ones((m,0))])                               
    In [32]: a                                                                                                   
    Out[32]: array([], shape=(10, 0), dtype=float64)
    

    将 (m,0) 替换为 (m,1),我们得到所需的 (10,1) 数组:

    In [33]: a = np.vstack([(np.tile(np.array([np.inf]), (m, 1))),np.ones((m,1))]) 
    

    stack 添加一个维度 - 这不是您想要的:

    In [35]: a = np.stack([(np.tile(np.array([np.inf]), (m, 1))),np.ones((m,1))])                                
    In [36]: a.shape                                                                                             
    Out[36]: (2, 5, 1)
    

    虽然有一个简单的起始形状,但我们得到 2 行:

    In [37]: a = np.stack([(np.tile(np.array([np.inf]), (m,))),np.ones((m))])                                    
    In [38]: a.shape                                                                                             
    Out[38]: (2, 5)
    

    实际上,您的stack 的问题是错误的)。这是正确的:

    In [50]: np.stack((np.tile(np.array([np.inf]), (m, 0)),np.ones((m,0))))                                      
    Out[50]: array([], shape=(2, 5, 0), dtype=float64)
    

    您的结束 ) 在 tile 之后,因此 np.ones() 表达式位于 axis 参数位置。

    【讨论】:

    • 感谢您的解释。我找到了np.stack 返回错误的原因。这是因为np.onesnp.zeros。我必须在列索引 np.zeros((m,1))np.ones((m,1)) 中分配 1
    【解决方案3】:

    因此,如果我正确理解了您的预期结果,您可能会这样做来生成矩阵。

    m = 5 #or whatever
    
    a = np.ones((2, m)) #create a matrix 2 x m of ones
    a[0] = np.inf #replace first row with infinites
    

    a 是:

    array([[inf, inf, inf, inf, inf],
           [ 1.,  1.,  1.,  1.,  1.]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2019-08-04
      相关资源
      最近更新 更多