如何在Python中创建稀疏矩阵?

PHPz
풀어 주다: 2023-09-05 15:49:06
앞으로
1072명이 탐색했습니다.

如何在Python中创建稀疏矩阵?

在本文中,我们将向您展示什么是稀疏矩阵以及如何在 python 中创建稀疏矩阵。

什么是稀疏矩阵?

稀疏矩阵是大多数元素为0的矩阵。也就是说,矩阵仅包含少数位置的数据。稀疏矩阵消耗的大部分内存都是由零组成的。

例如 -

M = [
   [1, 0, 0, 0],
   [0, 0, 3, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 2]
]
로그인 후 복사

使用二维数组来表示稀疏矩阵会浪费大量内存,因为矩阵中的零在大多数情况下都是无用的。因此,我们不是将零与非零元素一起保存,而是只存储非零元素。这涉及使用三元组来存储非零元素(行、列、值)。

自然语言处理(NLP)和数据编码都大量使用稀疏矩阵。如果大多数矩阵元素为 0,则存储所有矩阵元素的存储成本会很高。

这是因为我们只有几个数据点,并且大部分存储空间都被冗余零占用。

稀疏矩阵的优点

以下是使用稀疏矩阵而不是简单矩阵的两个主要优点 -

  • 存储 - 因为非零元素比零少,所以可以使用更少的内存来单独存储这些元素。

  • 计算时间 - 通过逻辑创建仅遍历非零元素的数据结构可以节省计算时间。

如何在Python中创建稀疏矩阵?

Python 中的 SciPy 提供了使用各种数据结构创建稀疏矩阵以及将稠密矩阵转换为稀疏矩阵的工具。

在Python中,我们可以使用以下函数创建稀疏矩阵 -

  • csr_matrix() 函数 - 以压缩稀疏行格式创建稀疏矩阵,

  • csc_matrix() 函数 - 以压缩稀疏列格式创建稀疏矩阵。,,

方法1.使用csr_matrix()函数创建稀疏矩阵

它以压缩稀疏格式创建稀疏矩阵。

语法

scipy.sparse.csr_matrix(shape=None, dtype=None)
로그인 후 복사

参数

  • shape - 它是矩阵的形状

  • dtype - 它是矩阵的数据类型

算法(步骤)

以下是执行所需任务所需遵循的算法/步骤 -

  • 使用 import 关键字,导入带有别名 (np) 的 numpy 模块。

  • 使用 import 关键字,从 scipy 模块导入 csr_matrix 函数。

  • 使用csr_matrix()函数创建int数据类型的3 * 3稀疏矩阵(row格式)并使用toarray转换为数组() 函数。

  • 打印生成的稀疏矩阵。

示例

以下程序使用 csr_matrix() 函数返回稀疏矩阵 (3x3) -

# importing numpy module with an alias name
import numpy as np

# importing csr_matrix function from scipy module
from scipy.sparse import csr_matrix

# Using csr_matrix function to create a 3 * 3 sparse matrix of int datatype
# and converting into array
sparse_matrix = csr_matrix((3, 3), dtype = np.int8).toarray()

# printing the resultant sparse matrix
print("The resultant sparse matrix:\n", sparse_matrix)
로그인 후 복사

输出

执行时,上述程序将生成以下输出 -

The resultant sparse matrix:
 [[0 0 0]
 [0 0 0]
 [0 0 0]]
로그인 후 복사
로그인 후 복사

方法 2. 使用给定 Numpy 数组的 csr_matrix() 函数创建稀疏矩阵

算法(步骤)

以下是执行所需任务所需遵循的算法/步骤 -

  • 使用 import 关键字,导入带有别名 (np) 的 numpy 模块。

  • 使用 import 关键字,从 scipy 模块导入 csr_matrix 函数。

  • 使用numpy.array()函数创建数组(返回一个ndarray。ndarray是满足给定要求的数组对象)

示例

# importing numpy module with alias name
import numpy as np

# importing csr_matrix function from scipy module
from scipy.sparse import csr_matrix

# Giving rows and columns values
rows = np.array([0, 1, 0, 2, 1, 1])
columns = np.array([1, 0, 0, 2, 1, 2])

# Giving array data
arrayData = np.array([1, 3, 2, 5, 7, 6])

# Using csr_matrix function to create a 3x3 sparse matrix
sparse_matrix = csr_matrix((arrayData, (rows, columns)),
   shape = (3, 3)).toarray()

# print the resultant sparse matrix
print("The resultant sparse matrix:\n", sparse_matrix)
로그인 후 복사

输出

执行时,上述程序将生成以下输出 -

The resultant sparse matrix:
 [[2 1 0]
 [3 7 6]
 [0 0 5]]
로그인 후 복사
로그인 후 복사

方法 3.使用 csc_matrix() 函数创建稀疏矩阵

它以压缩稀疏列格式创建稀疏矩阵。

语法

scipy.sparse.csc_matrix(shape=None, dtype=None)
로그인 후 복사

参数

  • shape - 它是矩阵的形状

  • dtype - 它是矩阵的数据类型

算法

以下是执行所需任务所需遵循的算法/步骤 -

  • 使用 import 关键字,导入带有别名 (np) 的 numpy 模块。

  • 使用 import 关键字,从 scipy 模块导入 csc_matrix 函数。

  • 使用csc_matrix()函数创建int数据类型的3 * 3稀疏矩阵(格式)并使用toarray转换为数组() 函数。

  • 打印生成的稀疏矩阵。

示例

以下程序使用 csc_matrix() 函数以列格式返回稀疏矩阵 (3x3) -

# importing numpy module with an alias name
import numpy as np

# importing csc_matrix function from scipy module
from scipy.sparse import csc_matrix

# Using csc_matrix function to create a 3 * 3 sparse matrix of int datatype
# and converting into array
sparse_matrix = csc_matrix((3, 3), dtype = np.int8).toarray()

# printing the resultant sparse matrix
print("The resultant sparse matrix:\n", sparse_matrix)
로그인 후 복사

输出

执行时,上述程序将生成以下输出 -

The resultant sparse matrix:
 [[0 0 0]
 [0 0 0]
 [0 0 0]]
로그인 후 복사
로그인 후 복사

方法 4. 使用给定 Numpy 数组的 csc_matrix() 函数创建稀疏矩阵

示例

以下程序使用 csc_matrix() 函数以整数列格式返回稀疏矩阵 (3x3) -

import numpy as np
# importing csc_matrix function from scipy module
from scipy.sparse import csc_matrix

# Giving rows and columns values
rows = np.array([0, 1, 0, 2, 1, 1])
columns = np.array([1, 0, 0, 2, 1, 2])

# Giving array data
arrayData = np.array([1, 3, 2, 5, 7, 6])

# Using csc_matrix function to create a 3x3 sparse matrix in column format
sparse_matrix = csc_matrix((arrayData, (rows, columns)),
   shape = (3, 3)).toarray()

# print the resultant sparse matrix
print("The resultant sparse matrix:\n", sparse_matrix)
로그인 후 복사

输出

执行时,上述程序将生成以下输出 -

The resultant sparse matrix:
 [[2 1 0]
 [3 7 6]
 [0 0 5]]
로그인 후 복사
로그인 후 복사

结论

在本教程中,我们学习了四种在 Python 中生成稀疏矩阵的不同方法。我们还学习了如何从 numpy 数组生成稀疏矩阵。

위 내용은 如何在Python中创建稀疏矩阵?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!