数据处理与可视化(机器学习算法原理与实践)

数据的导入和内存管理
1.数据表文件的读取
由于现在大多数系统内存都在几个G,因此小点的数据表处理比较简单,可以直接读入内存并结构化
下面例子是用python读取数据表文件,并将其存到矩阵中,并输出矩阵的行、列数
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import sys  
  4. import os  
  5. from numpy import *  
  6.   
  7. # 配置utf-8输出环境  
  8. reload(sys)  
  9. sys.setdefaultencoding('utf-8')  
  10.   
  11. #数据文件转矩阵  
  12. # path: 数据文件路径  
  13. # delimiter: 文件分隔符  
  14. def file2matrix(path,delimiter):  
  15.     recordlist = []  
  16.     fp = open(path,"rb")     # 读取文件内容  
  17.     content = fp.read()  
  18.     fp.close()  
  19.     rowlist = content.splitlines()     # 按行转换为一维表  
  20.     # 逐行遍历  
  21.     # 结果按分隔符分割为行向量  
  22.     recordlist =[ row.split(delimiter) for row in rowlist if row.strip()]  
  23.     return mat(recordlist)    # 返回转换后的矩阵形式  
  24.   
  25. root = "testdata" #数据文件所在路径  
  26. pathlist = os.listdir(root) # 获取路径下所有数据文件  
  27. for path in pathlist:  
  28.     recordmat = file2matrix(root+"/"+path,"\t") # 文件到矩阵的转换  
  29.     print shape(recordmat) # 输出解析后矩阵的行、列数  
输出结果如下
 
2.对象的持久化
有时候我们希望数据以对象的方式保存,python的ePicke模块支持对象的读写
下面例子将转换为矩阵的数据持久化为对象的文件,并读取序列化后的文件
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import sys  
  4. import os  
  5. from numpy import * #导入序列化库  
  6. import cPickle as pickle  
  7. # 配置utf-8输出环境  
  8. reload(sys)  
  9. sys.setdefaultencoding('utf-8')  
  10.   
  11. #数据文件转矩阵  
  12. # path: 数据文件路径  
  13. # delimiter: 文件分隔符  
  14. def file2matrix(path,delimiter):  
  15.     recordlist = []  
  16.     fp = open(path,"rb")     # 读取文件内容  
  17.     content = fp.read()  
  18.     fp.close()  
  19.     rowlist = content.splitlines()     # 按行转换为一维表  
  20.     # 逐行遍历  
  21.     # 结果按分隔符分割为行向量  
  22.     recordlist =[ row.split(delimiter) for row in rowlist if row.strip()]  
  23.     return mat(recordlist)    # 返回转换后的矩阵形式  
  24.   
  25. root = "testdata" #数据文件所在路径  
  26.   
  27. pathlist = os.listdir(root) # 获取路径下所有数据文件  
  28.   
  29. recordmat = [file2matrix(root+"/"+path,"\t") for path in pathlist]  
  30.   
  31. # 转换为对象文件  
  32. file_obj = open(root+"/recordmat.dat", "wb")  
  33. pickle.dump(recordmat[0],file_obj) #将生成的矩阵独享保存到指定位置  
  34. file_obj.close()  
  35.   
  36. # 读取序列化后的文件  
  37. read_obj = open(root+"/recordmat.dat", "rb")  
  38. readmat = pickle.load(read_obj) #从指定位置读取对象  
  39. print shape(readmat)  
输出结果如下
3.高效读取大文本文件
当遇到大文本文件时(几G,几十G,超过内存大小),可以使用如下函数逐行读取,逐行处理
如下例子读取了文件的前10行
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import sys   
  4. import os  
  5. from numpy import *  
  6.   
  7. # 配置utf-8输出环境  
  8. reload(sys)  
  9. sys.setdefaultencoding('utf-8')  
  10.   
  11. # 按行读文件,读取指定行数  
  12. # nmax=0按行读取全部  
  13. def readfilelines(path,nmax=0):  
  14.     fp = open(path,"rb")  
  15.     ncount = # 已读取行  
  16.     while True:  
  17.         content = fp.readline()             
  18.         # 判断是否到文件尾,是否读取到  
  19.         if content =="" or (ncount>=nmax and nmax!=0):  
  20.             break  
  21.         yield content  # 返回读取的行  
  22.         if nmax != 0 :     ncount += 1  
  23.     fp.close()  
  24.   
  25. path = "testdata/01.txt" #数据文件所在路径  
  26. # 读取10行,  
  27. for line in readfilelines(path,nmax=10):  
  28.     print line.strip()  
输出结果如下
 
表与线性结构的可视化
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import numpy as np  
  4. import matplotlib.pyplot as plt  
  5.   
  6. # 曲线数据加入噪声  
  7. x = np.linspace(-5,5,200);  
  8. y = np.sin(x);# 给出y与x的基本关系  
  9. yn = y+np.random.rand(1,len(y))*1.5 ;    # 加入噪声的点集  
  10.   
  11. # 绘图  
  12. fig = plt.figure()  
  13. ax = fig.add_subplot(111)  
  14. ax.scatter(x,yn,c='blue',marker='o')  
  15. ax.plot(x,y+0.75,'r')  
  16. plt.show()  
 
树与分类结构的可视化
因为MatPlotlib没有提供专门绘制树的API,所以这里用了treePlotter
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import numpy as np  
  4. import matplotlib.pyplot as plt  
  5. import treePlotter as tp  
  6.   
  7. # 绘制树  
  8. myTree = {'root': {0: 'leaf node', 1: {'level 2': {0: 'leaf node', 1: 'leaf node'}},2:{'level2': {0: 'leaf node', 1: 'leaf node'}}}}  
  9. tp.createPlot(myTree)  
 
图与网络结构的可视化
图和网络结构是神经网络和贝叶斯网络中重要的数据结构,完整的结构一般使用dict加list进行存储。
[python]  view plain  copy
 
  1. Node = {'node name':node_info}  
  2. Arc = {'arc name':list[node1,node2,…]}  
在算法中,经常简化存储为邻接矩阵的形式,使用NumPy的矩阵结构存储点坐标;弧的坐标使用距离公式计算。可视化时可以生成x轴的list和y轴的list显示在图片中。
[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import numpy as np  
  4. from numpy import *  
  5. import matplotlib.pyplot as plt  
  6.   
  7. # nodelist = ["city1","city2","city3","city4","city5","city6","city7","city8"]  
  8. dist = mat([[0.1,0.1],[0.9,0.5],[0.9,0.1],[0.45,0.9],[0.9,0.8],[0.7,0.9],[0.1,0.45],[0.45,0.1]])  
  9. m,n = shape(dist)  
  10. # 绘图  
  11. fig = plt.figure()  
  12. ax = fig.add_subplot(111)  
  13. ax.scatter(dist.T[0],dist.T[1],c='blue',marker='o',s=100)  
  14. for point in dist.tolist():  
  15.     plt.annotate("("+str(point[0])+", "+str(point[1])+")",xy = (point[0],point[1]))     
  16. xlist = []  
  17. ylist = []  
  18. for px,py in zip(dist.T.tolist()[0],dist.T.tolist()[1]):  
  19.     xlist.append([px])  
  20.     ylist.append([py])  
  21. # print xlist  
  22. # print ylist  
  23. ax.plot(xlist,ylist,'r')  
  24. plt.show()  
 

猜你喜欢

转载自www.cnblogs.com/judejie/p/9029031.html
今日推荐