python numpy 使用笔记 矩阵操作
2016-04-14 21:39
746 查看
(原创文章转载请标注来源)
在学习机器学习的过程中经常会用到矩阵,那么使用numpy扩展包将是不二的选择
建议在平Python中用多维数组(array)代替矩阵(matrix)
入门请考 http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#
import numpy np
1. 读写数组,这里可以看成矩阵
2. 使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变:
3.transpose()对数组进行转置
4. 矩阵运算
5. 求行列大小
6. 求最值
7. 求第三列等于1的个数
8. 求一组随机数组
9. 组合两个数组
10. 求和 和 计算平均数
11.求交集
12.条件查询
13.矩阵写文件 追加 方式
未完。。补充中。。欢迎讨论
在学习机器学习的过程中经常会用到矩阵,那么使用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[:,:])
未完。。补充中。。欢迎讨论
相关文章推荐
- ToDo-List-><学习Python>
- python爬虫--BeautifulSoup的简单用法
- Python实现ARCGIS栅格计算器con函数功能
- Python叠加两幅栅格图像
- python学习12-算法
- python 第一天
- Libsvm学习-3 Libsvm的使用说明
- 64位UBUNTU 下安装和配置使用python的spark
- 【Python爬虫】入门知识
- 【Python爬虫】入门知识
- Python 爬虫学习2 向网页提交数据
- Python Web框架Tornado运行和部署
- 在Python Web项目中使用Jenkins进行持续集成
- ubuntu上用python安装扩展包遇到的一些问题
- libsvm学习-1 libsvm-3.21在Python-3.4.4, Pycharm, windows环境下的安装过程
- python +selenium+phantomjs 登录爬取新浪微博动态js页面
- Python学习
- Python 爬虫学习1
- Python日常
- MySQL+Python:安装MySQL-python