在 Julia 中,如何对稀疏矩阵进行列归一化? [英] In Julia, How can I column-normalize a sparse matrix?

查看:40
本文介绍了在 Julia 中,如何对稀疏矩阵进行列归一化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 sparse(i, j, k) 构造函数构造了一个稀疏矩阵,那么我该如何规范化矩阵的列(以便每列总和为 1)?在创建矩阵之前,我无法有效地规范化条目,因此感谢您提供任何帮助.谢谢!

If I have constructed a sparse matrix using the sparse(i, j, k) constructor, how can I then normalize the columns of the matrix (so that each column sums to 1)? I cannot efficiently normalize the entries before I create the matrix, so any help is appreciated. Thanks!

推荐答案

最简单的方法是广播除以列的总和:

The easiest way would be a broadcasting division by the sum of the columns:

julia> A = sprand(4,5,.5)
       A./sum(A,1)
4x5 Array{Float64,2}:
 0.0        0.0989976  0.0        0.0       0.0795486
 0.420754   0.458653   0.0986313  0.0       0.0
 0.0785525  0.442349   0.0        0.856136  0.920451
 0.500693   0.0        0.901369   0.143864  0.0

……但它看起来还没有针对稀疏矩阵进行优化,并且回退到一个完整的矩阵.所以一个简单的循环遍历列就可以了:

… but it looks like that hasn't been optimized for sparse matrices yet, and falls back to a full matrix. So a simple loop to iterate over the columns does the trick:

julia> for (col,s) in enumerate(sum(A,1))
         s == 0 && continue # What does a "normalized" column with a sum of zero look like?
         A[:,col] = A[:,col]/s
       end
       A
4x5 sparse matrix with 12 Float64 entries:
    [2, 1]  =  0.420754
    [3, 1]  =  0.0785525
    [4, 1]  =  0.500693
    [1, 2]  =  0.0989976
    [2, 2]  =  0.458653
    [3, 2]  =  0.442349
    [2, 3]  =  0.0986313
    [4, 3]  =  0.901369
    [3, 4]  =  0.856136
    [4, 4]  =  0.143864
    [1, 5]  =  0.0795486
    [3, 5]  =  0.920451

julia> sum(A,1)
1x5 Array{Float64,2}:
 1.0  1.0  1.0  1.0  1.0

这完全在稀疏矩阵中工作并且就地完成(尽管它仍在为每个列切片分配新的稀疏矩阵).

This works entirely within sparse matrices and is done in-place (although it is still allocating new sparse matrices for each column slice).

这篇关于在 Julia 中,如何对稀疏矩阵进行列归一化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆