• 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
     ',a)
    print('the result is
     ',b)

     

    3.transpose()对数组进行转置

    print('the transpose is
     ',b.transpose())#转置

     

    4. 矩阵运算

    np.dot() #矩阵的乘法
    print('the result is
     ',np.dot(a,b))#矩阵乘
    np.linalg.inv() #求矩阵的逆
    print('the inverse is
     ',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('[','')+'
    '
      fileObject.weite(tmp)
    fileObject.close()
    b = np.loadtxt('result.txt',delimiter=',')#同样可以读出矩阵
    print(b[:,:]) 

     

    未完。。补充中。。欢迎讨论

     

  • 相关阅读:
    C++new失败的处理
    [转]va_start和va_end使用详解
    zookeeper的一些异常总结
    无法产生coredump的问题
    [译]AMQP 0-9-1 Quick Reference : basic
    阿里巴巴分布式数据库同步系统(解决中美异地机房)
    第一步(搭建阿里云主机服务器): 如何在远程Linux服务器上搭建Nginx
    iOS响应事件传递, nextResponder研究
    五个在Safari浏览器上的实用快捷键使用
    git three
  • 原文地址:https://www.cnblogs.com/shuaishuai-it/p/5392880.html
Copyright © 2020-2023  润新知