python numpy 使用筆記 矩陣操作


(原創文章轉載請標注來源)

在學習機器學習的過程中經常會用到矩陣,那么使用numpy擴展包將是不二的選擇

建議在平Python中用多維數組(array)代替矩陣(matrix)

入門請考 http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#

import numpy np

1. 讀寫數組,這里可以看成矩陣

#返回值格式(評分,信任表,用戶個數,項目個數)
   a = np.arange(0,12,0.5).reshape(4,-1)   np.savetxt("a.txt", a) # 缺省按照'%.18e'格式保存數據,以空格分隔
   np.loadtxt("a.txt")   np.loadtxt('a.txt',dtype='int')#設置讀出的數據類型

 

2. 使用數組的reshape方法,可以創建一個改變了尺寸的新數組,原數組的shape保持不變:

a = np.arange(4).reshape(2,2) b = np.arange(6).reshape(2,3) print('the result is\n ',a) print('the result is\n ',b)

 

3.transpose()對數組進行轉置

print('the transpose is\n ',b.transpose())#轉置

 

4. 矩陣運算

np.dot() #矩陣的乘法 print('the result is\n ',np.dot(a,b))#矩陣乘
np.linalg.inv() #求矩陣的逆 print('the inverse is\n ',np.linalg.inv(a))#逆矩陣

 

5. 求行列大小

(m,n) = a.shape#求行列個數

 

6. 求最值

temp1 = np.max(a[:,0]) temp2 = np.min(a[:,0])

 

7. 求第三列等於1的個數

np.sum(a[:,2]==1)



8.
求一組隨機數組

randIndices = np.random.permutation(4) ans=array[[3,0,2,1]]

9. 組合兩個數組

np.vstack((a,b))#縱向結合,保證列數相同 注意雙括號
np.hstack((a,b))#橫向結合,保證行數相同

 

10. 求和 和 計算平均數

 

np.sum(a,0)#0代表求得是各列的和
 np.mean(a,1)#1代表求得各行的平均數

  

11.求交集

np.intersectld(a[0,:],b[0,:])#求兩個一維數組的交集

 

12.條件查詢

np.where(a>5)#找到所有滿足條件的位置
 np.where(a>5,0,1)#找到這些值滿足賦值為0,不滿足賦值為1

 

13.矩陣寫文件 追加 方式

fileObject = open('result.txt','a')#追加的方式打開文件
a = [[1,2,3] ,[3,4,5] , [4,5,6]]#存取list
for i in a:   tmp = str(i)   tmp = tmp.replace('[','')   tmp = tmp.replace('[','')+'\n'   fileObject.weite(tmp) fileObject.close() b = np.loadtxt('result.txt',delimiter=',')#同樣可以讀出矩陣
print(b[:,:]) 

 

未完。。補充中。。歡迎討論

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM