【问题标题】:Matrix/array operations inside a python functionpython函数中的矩阵/数组操作
【发布时间】:2020-12-11 02:26:33
【问题描述】:

我正在尝试使用 python 函数的内容来制作等高线图。例如我尝试:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# Building my equation from a series of matrix operation

def func_M(X, Y): 

    z_mat = np.array([[X**2, Y], 
                       [Y, X]]) 
    z_other = np.array([[X],
                        [Y]])
    z_matInv = (np.linalg.inv(z_mat))
    z_final=np.dot(z_matInv,z_other)

    return z_final[0][0]

# print out the return of the function evaluated at X = .1.5, and Y = 2.

print func_M(1.5,2.)

# Building and x and y grid to plot:

x = np.arange(-5, 5, 0.01)
y = np.arange(-5, 5, 0.01)
xx, yy = np.meshgrid(x, y, sparse=True)

# Making the z component and contour plotting function:

#z_plot_M = func_M(xx,yy)
#h = plt.contourf(x,y,z_plot_M)
#plt.show()

因此,print 函数打印出 2.8,这是在 x = 1.0 和 y =2.0 处计算的最终矩阵的第一个元素。

但是,如果我尝试将其评估为计数(注释位),则它不起作用。

这是我用作基础的简单代码:

x = np.arange(-5, 5, 0.01)
y = np.arange(-5, 5, 0.01)
xx, yy = np.meshgrid(x, y, sparse=True)

def func_eq(X, Y):
    z = np.sin(X**2) + np.sin(Y**2)
    return z

z_plot = func_eq(xx,yy)

h = plt.contourf(x,y,z_plot)
plt.show()

这是有原因的,但是当我有矩阵而不是简单的方程时,它没有?第一种情况有简单的解决方法吗?

【问题讨论】:

  • 这与代码是在函数内部还是外部无关。 z_mat 不是矩阵 - 它是 3 维的。你不能对不是矩阵的东西进行矩阵求逆。
  • 你可以,如果我在函数外做同样的操作并且它工作正常。
  • No it doesn't. (另外,哎呀,不是 3D - 我错过了这样一个事实,即您将 xxyy 传递为 XYz_mat 是多维锯齿状的object dtype。)
  • 无论您认为z_mat 是什么,都不是。
  • 我实际上是在查看一个在函数工作鳍之外的工作代码。但是,该代码运行,问题不在于计算是绘图功能。

标签: python numpy matrix array-broadcasting matrix-inverse


【解决方案1】:
In [263]: x = np.arange(-5, 5, 0.01)
     ...: y = np.arange(-5, 5, 0.01)
     ...: xx, yy = np.meshgrid(x, y, sparse=True)
     ...: 
In [264]: x.shape
Out[264]: (1000,)
In [265]: xx.shape
Out[265]: (1, 1000)
In [266]: yy.shape
Out[266]: (1000, 1)

通过指定spare=Truexxyy 具有不同的形状。他们一起广播,如xx+yy。但是尝试创建一个新数组,就像您创建对象 dtype 数组一样:

In [267]: z_other=np.array([[xx],[yy]])
<ipython-input-267-80e1b3aae946>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  z_other=np.array([[xx],[yy]])
In [268]: z_other.shape
Out[268]: (2, 1)

In [269]: z_mat = np.array([[xx**2, yy],
     ...:                        [yy, xx]])
<ipython-input-269-a02f5f8ab715>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  z_mat = np.array([[xx**2, yy],
In [270]: z_mat.shape
Out[270]: (2, 2)

并尝试在此类数组上执行数字 inv,会产生错误:

In [271]: np.linalg.inv(z_mat)
Traceback (most recent call last):
  File "<ipython-input-271-f9e7af1a2be5>", line 1, in <module>
    np.linalg.inv(z_mat)
  File "<__array_function__ internals>", line 5, in inv
  File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 546, in inv
    ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
TypeError: No loop matching the specified signature and casting was found for ufunc inv

====

删除sparse=True,生成2个二维数组:

In [272]: x = np.arange(-5, 5, 0.01)
     ...: y = np.arange(-5, 5, 0.01)
     ...: xx, yy = np.meshgrid(x, y)
In [273]: xx.shape, yy.shape
Out[273]: ((1000, 1000), (1000, 1000))

组合成一个 4d 数组。

In [274]: z_mat = np.array([[xx**2, yy],
     ...:                        [yy, xx]])
In [275]: z_mat.shape
Out[275]: (2, 2, 1000, 1000)

这符合规范 (...,M,M),应该产生 (2,2) 逆 - 除了这些数组是奇异的事实。

In [276]: C = np.linalg.inv(z_mat)
Traceback (most recent call last):
  File "<ipython-input-276-7ae416f9f924>", line 1, in <module>
    C = np.linalg.inv(z_mat)
  File "<__array_function__ internals>", line 5, in inv
  File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 546, in inv
    ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
  File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 88, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
LinAlgError: Singular matrix

非奇异数组由你来构建。

【讨论】:

  • 感谢您的评论,但这不是我正在做的。该函数独立于 xx 和 yy 的数组。我只尝试在所有矩阵运算完成后评估函数的返回。
  • 我试图展示func_M(xx,yy) 会产生的错误类型。如果那不是您正在做的事情,那么您为什么要生成 xx, yy 并带有此注释行。您还提到了一堆错误,但没有显示出来。如果您需要真正的帮助,请提出明确的问题!
  • 我明白了。我不知道如何构建一个数组,否则。我只是假设它会为 x 和 y 选择一个值并执行它,然后是下一个,依此类推....我的意思是,这对于函数内的简单方程很有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多