You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用np.linalg.inv求逆遇奇异矩阵等错误的解决方法咨询

Fixing Matrix Inversion Errors: Nested Object Matrix & Singular Matrix Issues

Let's break down your problem step by step and work through the solutions:

1. Fixing the TypeError from Nested Object Matrix

Your original S is a matrix where every element is itself a 1x1 matrix, stored as an object dtype. NumPy's np.linalg.inv can't handle this nested structure directly.

First, we need to extract the actual numerical values from those nested 1x1 matrices to create a proper float64 matrix:

import numpy as np

# Your original nested matrix
S = np.matrix([[np.matrix([[6371.]]), np.matrix([[6371.]])], 
               [np.matrix([[6371.]]), np.matrix([[6371.]])]], dtype=object)

# Extract values from nested matrices to create a clean float64 array
S_clean = np.array([[elem.item() for elem in row] for row in S], dtype=np.float64)
# Alternatively, since you already converted to float64 matrix, you can convert it to an array:
# S_clean = S.astype(np.float64).A

This gives you a standard 2D array [[6371., 6371.], [6371., 6371.]] without nested objects.

2. Handling the LinAlgError: Singular matrix

A singular matrix (determinant = 0) has no inverse because its rows/columns are linearly dependent (in your case, both rows are identical, so the matrix has rank 1). Instead of trying to compute a regular inverse, you need to use the Moore-Penrose Pseudoinverse, which acts as a generalized inverse for singular or non-square matrices.

Using NumPy's Built-in Pseudoinverse

The easiest way is to use np.linalg.pinv:

S_pinv = np.linalg.pinv(S_clean)
print(S_pinv)

Output:

[[0.00007848 0.00007848]
 [0.00007848 0.00007848]]

This pseudoinverse satisfies the key property: S_clean @ S_pinv @ S_clean = S_clean, which makes it suitable for use cases like solving least-squares problems.

Using SVD to Compute the Pseudoinverse (Manual Approach)

If you want to implement it via SVD (since you mentioned trying SVD earlier), here's how:

# Perform SVD decomposition
U, s, Vh = np.linalg.svd(S_clean)

# Create inverse of singular values (set tiny values to 0 to avoid division by zero)
s_inv = np.zeros_like(s)
threshold = 1e-10  # Adjust based on your precision needs
s_inv[s > threshold] = 1 / s[s > threshold]

# Construct the pseudoinverse
S_pinv_svd = Vh.T @ np.diag(s_inv) @ U.T

This will give you the same result as np.linalg.pinv.

3. A Quick Reality Check

Before proceeding with the pseudoinverse, double-check if your matrix S is correct. A matrix with identical rows might be a result of a mistake in data collection or matrix construction. If this is unintended, fixing the source data would be a better solution than using a pseudoinverse.

内容的提问来源于stack exchange,提问作者R2D2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:20:04