热线电话:13121318867

登录
2019-01-16 阅读量: 800
如何将数据分类

对数据进行分类

将数据存储到项目中后,我们现在开始构建分类器。对于分类器,我们将创建一个新函数Classify。它将输入我们想要分类的项目,项目列表和k,最近邻居的数量。

如果k大于数据集的长度,我们不会继续进行分类,因为我们不能拥有比数据集中项目总数更多的最近邻居。(或者我们可以将k设置为长度而不是返回错误消息)

我们想要计算要分类的项目与训练集中的所有项目之间的距离,最后保持k个最短距离。为了保持当前最近的邻居,我们使用一个叫做邻居的列表。每个元素至少包含两个值,一个用于与要分类的项目的距离,另一个用于邻居所在的类别。我们将通过广义欧几里德公式(对于n维度)计算距离。然后,我们将选择大部分时间出现在邻居中的班级,这将是我们的选择。在代码中:

def Classify(nItem, k, Items):

if(k > len(Items)):

# k is larger than list

# length, abort

return "k larger than list length";

# Hold nearest neighbors.

# First item is distance,

# second class

neighbors = [];

for item in Items:

# Find Euclidean Distance

distance = EuclideanDistance(nItem, item);

# Update neighbors, either adding

# the current item in neighbors

# or not.

neighbors = UpdateNeighbors(neighbors, item, distance, k);

# Count the number of each

# class in neighbors

count = CalculateNeighborsClass(neighbors, k);

# Find the max in count, aka the

# class with the most appearances.

return FindMax(count);

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子