fig = plt.figure()
ax = fig.add_subplot(111)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
plt.xlabel(‘Percentage of Time Spent Playing Video Games’)
plt.ylabel(‘Liters of Ice Cream Consumed Per Week’)
plt.show()
3D图:
import numpy
import kNN
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection=‘3d’)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax.set_xlabel(‘mei nian huo qu de fei xing chang ke li cheng shu’)
ax.set_ylabel(‘wan you xi shi jian bi li’)
ax.set_zlabel(‘mei zhou xiao hao de bing qi li shuliang’)
plt.show()
多图:
import numpy
import kNN
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(311)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax1.scatter(datingDataMat[:,0],datingDataMat[:,1],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax1.set_xlabel(‘fly’)
ax2 = fig.add_subplot(312)
ax2.scatter(datingDataMat[:,0],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax2 = fig.add_subplot(313)
ax2.scatter(datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
plt.show()
不熟悉的函数:
add_subplot:用于指定图像的位置,例如111,指图像分成一行一列,在第一幅图上画
scatter:画散点图,必须输入的有x,y坐标,可选项有颜色形状等
zero:创建0矩阵
归一化:
处理不同取值范围的特征值时,通常需要将数值未硬化,如果将取值范围处理为0到1或者-1到1之间,下面公式可以将任意取值范围的特征值转化为0到1的区间内
newValue = (oldValue-min)/(max-min)
min,max分别是数据集中特征值最大值和最小值,程序如下
def autoNum(dataSet):
#获取每一列的最小值
minVals = dataSet.min(0)
#获取每一列的最大值
maxVals = dataSet.max(0)
#最大值和最小值的差
ranges = maxVals - minVals
#将每一行归一化
normDataSet = numpy.zeros(numpy.shape(dataSet))
m = dataSet.shape[0]
normDataSet = dataSet - numpy.tile(minVals,(m,1))
normDataSet = normDataSet/numpy.tile(ranges,(m,1))
return normDataSet,ranges,minVals
容易搞错的是min(0)返回的是每一列的最小值,而不是第0列的最小值,min()返回的是所有值的最小值,min