摘自《机器学习实践》第13章:
1 from numpy import * 2 import matplotlib 3 import matplotlib.pyplot as plt 4 5 def loadDataSet(fileName, delim='\t'): 6fr = open(fileName) 7stringArr = [line.strip().split(delim) for line in fr.readlines()] 8datArr = [map(float, line) for line in stringArr] 9return mat(datArr)10 11 def pca(dataMat, topNfeat = 999999):12meanVals = mean(dataMat, axis = 0)13meanRemoved = dataMat - meanVals14covMat = cov(meanRemoved, rowvar = 0)15eigVals, eigVects = linalg.eig(mat(covMat))16eigValInd = argsort(eigVals)17eigValInd = eigValInd[: - (topNfeat + 1): -1]18redEigVects = eigVects[:, eigValInd]19lowDDataMat = meanRemoved * redEigVects20reconMat = (lowDDataMat * redEigVects.T) + meanVals21return lowDDataMat, reconMat22 23 if __name__ == "__main__":24dataMat = loadDataSet('testSet.txt')25lowDMat, reconMat = pca(dataMat, 1)26fig = plt.figure()27ax = fig.add_subplot(111)28ax.scatter(dataMat[:, 0].flatten().A[0], dataMat[:, 1].flatten().A[0], marker='^', s = 90)29ax.scatter(reconMat[:, 0].flatten().A[0], reconMat[:, 1].flatten().A[0], marker='o', s = 50, c='red')30plt.show()
输入数据格式: 文本文件,每行是两个以TAB键分隔的浮点数。
附运行结果: