(原创文章转载请标注来源)html
在学习机器学习的过程当中常常会用到矩阵,那么使用numpy扩展包将是不二的选择数组
建议在平Python中用多维数组(array)代替矩阵(matrix)dom
入门请考 http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#机器学习
import numpy np学习
1. 读写数组,这里能够当作矩阵spa
#返回值格式(评分,信任表,用户个数,项目个数)
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保持不变:.net
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()对数组进行转置code
print('the transpose is\n ',b.transpose())#转置
4. 矩阵运算htm
np.dot() #矩阵的乘法 print('the result is\n ',np.dot(a,b))#矩阵乘
np.linalg.inv() #求矩阵的逆 print('the inverse is\n ',np.linalg.inv(a))#逆矩阵
5. 求行列大小blog
(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[:,:])
未完。。补充中。。欢迎讨论