K-近邻算法实现
Aug042019
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import operator
def main():
group, labels = createTrainingDataSet()
label = classify0([0, 0], group, labels, 3)
print(label)
def dating_test():
datingDataMat, datingLabels = file2matrix("datingTestSet2.txt")
datingDataMat, a, b = autoNorm(datingDataMat)
print(datingDataMat[0:15])
print(datingLabels[0:15])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2],
15.0 * np.array(datingLabels), 15.0 * np.array(datingLabels))
ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1],
15.0 * np.array(datingLabels), 15.0 * np.array(datingLabels))
plt.show()
def main_test():
# group, labels = createTrainingDataSet()
# print(group.shape)
# print(np.tile(np.array([1, 2]), (group.shape[0], 2)))
a = np.arange(15).reshape(3, 5)
print(a)
print(a.T)
print(a.ndim)
print(a.shape)
print(a.dtype)
def createTrainingDataSet():
group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
def classify0(inX, trainingDataSet, labels, k):
dataSetSize = trainingDataSet.shape[0]
diffMat = np.tile(inX, (dataSetSize, 1)) - trainingDataSet
# 将inX 平铺(复制)成跟训练集同样的行数
# 如果inX = [a,b], 训练集有2行,
# 则结果为 一个矩阵
# [[a,b],
# [a,b]]
# 然后再和训练集做矩阵减法
sqDiffMat = diffMat ** 2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances ** 0.5
sortedDistIndices = distances.argsort()
classCount = {}
for i in range(k):
voteILabel = labels[sortedDistIndices[i]]
classCount[voteILabel] = classCount.get(voteILabel, 0) + 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) # get the number of lines in the file
returnMat = np.zeros((numberOfLines, 3)) # prepare matrix to return
classLabelVector = [] # prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split('\t')
returnMat[index, :] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat, classLabelVector
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataSet = np.zeros(np.shape(dataSet))
m = dataSet.shape[0]
normDataSet = dataSet - np.tile(minVals, (m, 1))
normDataSet = normDataSet / np.tile(ranges, (m, 1)) # element wise divide
return normDataSet, ranges, minVals
def datingClassTest():
hoRatio = 0.1
datingDataMat, datingLabels = file2matrix("datingTestSet2.txt")
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
numTestVecs = int(m * hoRatio)
errorCount = 0.0
for i in range(numTestVecs):
classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3)
print(f"the classifier came back with: {classifierResult}, the real answer is {datingLabels[i]}")
if classifierResult != datingLabels[i]:
errorCount += 1.0
print(f"the total error rata is {errorCount / float(numTestVecs)}")
def realP():
datingDataMat, datingLabels = file2matrix("datingTestSet2.txt")
normMat, ranges, minVals = autoNorm(datingDataMat)
inArr = np.array([50000, 10, 0.5])
r = classify0((inArr - minVals) / ranges, normMat, datingLabels, 3)
print(f"predict result is {r}")
if __name__ == '__main__':
datingClassTest()
realP()
# main()
# main_test()
# dating_test()
机器学习实战02 1.19 MB
微信赞赏 支付宝赞赏
本文固定链接: https://www.jack-yin.com/coding/ml/ml-algorithm/2795.html | 边城网事