99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀python實現(xiàn)稀疏矩陣示例代碼
python實現(xiàn)稀疏矩陣示例代碼
2017-09-09
收藏

python實現(xiàn)稀疏矩陣示例代碼

工程實踐中,多數(shù)情況下,大矩陣一般都為稀疏矩陣,所以如何處理稀疏矩陣在實際中就非常重要。本文以Python里中的實現(xiàn)為例,首先來探討一下稀疏矩陣是如何存儲表示的。

1.sparse模塊初探

python中scipy模塊中,有一個模塊叫sparse模塊,就是專門為了解決稀疏矩陣而生。本文的大部分內(nèi)容,其實就是基于sparse模塊而來的。

第一步自然就是導入sparse模塊

>>> from scipy import sparse
然后help一把,先來看個大概
>>> help(sparse)
直接找到我們最關(guān)心的部分:
Usage information
=================
 
There are seven available sparse matrix types:
 
  1. csc_matrix: Compressed Sparse Column format
  2. csr_matrix: Compressed Sparse Row format
  3. bsr_matrix: Block Sparse Row format
  4. lil_matrix: List of Lists format
  5. dok_matrix: Dictionary of Keys format
  6. coo_matrix: COOrdinate format (aka IJV, triplet format)
  7. dia_matrix: DIAgonal format
 
To construct a matrix efficiently, use either dok_matrix or lil_matrix.
The lil_matrix class supports basic slicing and fancy
indexing with a similar syntax to NumPy arrays. As illustrated below,
the COO format may also be used to efficiently construct matrices.
 
To perform manipulations such as multiplication or inversion, first
convert the matrix to either CSC or CSR format. The lil_matrix format is
row-based, so conversion to CSR is efficient, whereas conversion to CSC
is less so.
 
All conversions among the CSR, CSC, and COO formats are efficient,
linear-time operations.
通過這段描述,我們對sparse模塊就有了個大致的了解。sparse模塊里面有7種存儲稀疏矩陣的方式。接下來,我們對這7種方式來做個一一介紹。

2.coo_matrix
coo_matrix是最簡單的存儲方式。采用三個數(shù)組row、col和data保存非零元素的信息。這三個數(shù)組的長度相同,row保存元素的行,col保存元素的列,data保存元素的值。一般來說,coo_matrix主要用來創(chuàng)建矩陣,因為coo_matrix無法對矩陣的元素進行增刪改等操作,一旦矩陣創(chuàng)建成功以后,會轉(zhuǎn)化為其他形式的矩陣。 
>>> row = [2,2,3,2]
>>> col = [3,4,2,3]
>>> c = sparse.coo_matrix((data,(row,col)),shape=(5,6))
>>> print c.toarray()
[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 5 2 0]
 [0 0 3 0 0 0]
 [0 0 0 0 0 0]]

稍微需要注意的一點是,用coo_matrix創(chuàng)建矩陣的時候,相同的行列坐標可以出現(xiàn)多次。矩陣被真正創(chuàng)建完成以后,相應的坐標值會加起來得到最終的結(jié)果。

3.dok_matrix與lil_matrix

dok_matrix和lil_matrix適用的場景是逐漸添加矩陣的元素。doc_matrix的策略是采用字典來記錄矩陣中不為0的元素。自然,字典的key存的是記錄元素的位置信息的元祖,value是記錄元素的具體值。
>>> import numpy as np
>>> from scipy.sparse import dok_matrix
>>> S = dok_matrix((5, 5), dtype=np.float32)
>>> for i in range(5):
...   for j in range(5):
...       S[i, j] = i + j
...
>>> print S.toarray()
[[ 0. 1. 2. 3. 4.]
 [ 1. 2. 3. 4. 5.]
 [ 2. 3. 4. 5. 6.]
 [ 3. 4. 5. 6. 7.]
 [ 4. 5. 6. 7. 8.]]

lil_matrix則是使用兩個列表存儲非0元素。data保存每行中的非零元素,rows保存非零元素所在的列。這種格式也很適合逐個添加元素,并且能快速獲取行相關(guān)的數(shù)據(jù)。   
>>> from scipy.sparse import lil_matrix
>>> l = lil_matrix((6,5))
>>> l[2,3] = 1
>>> l[3,4] = 2
>>> l[3,2] = 3
>>> print l.toarray()
[[ 0. 0. 0. 0. 0.]
 [ 0. 0. 0. 0. 0.]
 [ 0. 0. 0. 1. 0.]
 [ 0. 0. 3. 0. 2.]
 [ 0. 0. 0. 0. 0.]
 [ 0. 0. 0. 0. 0.]]
>>> print l.data
[[] [] [1.0] [3.0, 2.0] [] []]
>>> print l.rows
[[] [] [3] [2, 4] [] []]

由上面的分析很容易可以看出,上面兩種構(gòu)建稀疏矩陣的方式,一般也是用來通過逐漸添加非零元素的方式來構(gòu)建矩陣,然后轉(zhuǎn)換成其他可以快速計算的矩陣存儲方式。

4.dia_matrix

這是一種對角線的存儲方式。其中,列代表對角線,行代表行。如果對角線上的元素全為0,則省略。

如果原始矩陣是個對角性很好的矩陣那壓縮率會非常高。

找了網(wǎng)絡上的一張圖,大家就很容易能看明白其中的原理。

5.csr_matrix與csc_matrix

csr_matrix,全名為Compressed Sparse Row,是按行對矩陣進行壓縮的。CSR需要三類數(shù)據(jù):數(shù)值,列號,以及行偏移量。CSR是一種編碼的方式,其中,數(shù)值與列號的含義,與coo里是一致的。行偏移表示某一行的第一個元素在values里面的起始偏移位置。

同樣在網(wǎng)絡上找了一張圖,能比較好反映其中的原理。

看看在python里怎么使用:
>>> from scipy.sparse import csr_matrix
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 2],
    [0, 0, 3],
    [4, 5, 6]])
怎么樣,是不是也不是很難理解。
我們再看看文檔中是怎么說的
  
Notes
| -----
|
| Sparse matrices can be used in arithmetic operations: they support
| addition, subtraction, multiplication, division, and matrix power.
|
| Advantages of the CSR format
|  - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
|  - efficient row slicing
|  - fast matrix vector products
|
| Disadvantages of the CSR format
|  - slow column slicing operations (consider CSC)
|  - changes to the sparsity structure are expensive (consider LIL or DOK)

不難看出,csr_matrix比較適合用來做真正的矩陣運算。

至于csc_matrix,跟csr_matrix類似,只不過是基于列的方式壓縮的,不再單獨介紹。

6.bsr_matrix

Block Sparse Row format,顧名思義,是按分塊的思想對矩陣進行壓縮

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }