码迷,mamicode.com
首页 > 编程语言 > 详细

python numpy 使用笔记--基本矩阵操作

时间:2016-04-14 22:34:17      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:

在学习机器学习的过程中经常会用到矩阵,那么使用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))#横向结合,保证行数相同

 

 

未完。。补充中

 

python numpy 使用笔记--基本矩阵操作

标签:

原文地址:http://www.cnblogs.com/shuaishuai-it/p/5392880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!