- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
鉴于我的知识数据库中有以下内容:
1 0 6 20 0 0 6 20
1 0 3 6 0 0 3 6
1 0 15 45 0 0 15 45
1 0 17 44 0 0 17 44
1 0 2 5 0 0 2 5
我希望能够找到以下向量的最近邻:
1 0 5 16 0 0 5 16
根据距离度量。所以在这种情况下,给定一个特定的阈值,我应该发现列出的第一个向量是给定向量的近邻。目前,我的知识数据库的大小约为数百万,因此计算每个点的距离度量然后进行比较证明是昂贵的。是否有任何替代方法可以显着加快实现这一目标?
我对几乎任何方法都持开放态度,包括在 MySQL 中使用空间索引(除了我不完全确定如何解决这个问题)或某种散列(这很好,但我也不完全相信当然)。
最佳答案
在 Python 中(来自 www.comp.mq.edu.au/):
def count_different_values(k_v1s, k_v2s):
"""kv1s and kv2s should be dictionaries mapping keys to
values. count_different_values() returns the number of keys in
k_v1s and k_v2s that don't have the same value"""
ks = set(k_v1s.iterkeys()) | set(k_v2s.iterkeys())
return sum(1 for k in ks if k_v1s.get(k) != k_v2s.get(k))
def sum_square_diffs(x0s, x1s):
"""x1s and x2s should be equal-lengthed sequences of numbers.
sum_square_differences() returns the sum of the squared differences
of x1s and x2s."""
sum((pow(x1-x2,2) for x1,x2 in zip(x1s,x2s)))
def incr(x_c, x, inc=1):
"""increments the value associated with key x in dictionary x_c
by inc, or sets it to inc if key x is not in dictionary x_c."""
x_c[x] = x_c.get(x, 0) + inc
def count_items(xs, x_c=None):
"""returns a dictionary x_c whose keys are the items in xs, and
whose values are the number of times each item occurs in xs."""
if x_c == None:
x_c = {}
for x in xs:
incr(x_c, x)
return x_c
def second(xy):
"""returns the second element in a sequence"""
return xy[1]
def most_frequent(xs):
"""returns the most frequent item in xs"""
x_c = count_items(xs)
return sorted(x_c.iteritems(), key=second, reverse=True)[0][0]
class kNN_classifier:
"""This is a k-nearest-neighbour classifer."""
def __init__(self, train_data, k, distf):
self.train_data = train_data
self.k = min(k, len(train_data))
self.distf = distf
def classify(self, x):
Ns = sorted(self.train_data,
key=lambda xy: self.distf(xy[0], x))
return most_frequent((y for x,y in Ns[:self.k]))
def batch_classify(self, xs):
return [self.classify(x) for x in xs]
def train(train_data, k=1, distf=count_different_values):
"""Returns a kNN_classifer that contains the data, the number of
nearest neighbours k and the distance function"""
return kNN_classifier(train_data, k, distf)
也是 www.umanitoba.ca/的另一个实现
#!/usr/bin/env python
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""
This module provides code for doing k-nearest-neighbors classification.
k Nearest Neighbors is a supervised learning algorithm that classifies
a new observation based the classes in its surrounding neighborhood.
Glossary:
distance The distance between two points in the feature space.
weight The importance given to each point for classification.
Classes:
kNN Holds information for a nearest neighbors classifier.
Functions:
train Train a new kNN classifier.
calculate Calculate the probabilities of each class, given an observation.
classify Classify an observation into a class.
Weighting Functions:
equal_weight Every example is given a weight of 1.
"""
import numpy
class kNN:
"""Holds information necessary to do nearest neighbors classification.
Members:
classes Set of the possible classes.
xs List of the neighbors.
ys List of the classes that the neighbors belong to.
k Number of neighbors to look at.
"""
def __init__(self):
"""kNN()"""
self.classes = set()
self.xs = []
self.ys = []
self.k = None
def equal_weight(x, y):
"""equal_weight(x, y) -> 1"""
# everything gets 1 vote
return 1
def train(xs, ys, k, typecode=None):
"""train(xs, ys, k) -> kNN
Train a k nearest neighbors classifier on a training set. xs is a
list of observations and ys is a list of the class assignments.
Thus, xs and ys should contain the same number of elements. k is
the number of neighbors that should be examined when doing the
classification.
"""
knn = kNN()
knn.classes = set(ys)
knn.xs = numpy.asarray(xs, typecode)
knn.ys = ys
knn.k = k
return knn
def calculate(knn, x, weight_fn=equal_weight, distance_fn=None):
"""calculate(knn, x[, weight_fn][, distance_fn]) -> weight dict
Calculate the probability for each class. knn is a kNN object. x
is the observed data. weight_fn is an optional function that
takes x and a training example, and returns a weight. distance_fn
is an optional function that takes two points and returns the
distance between them. If distance_fn is None (the default), the
Euclidean distance is used. Returns a dictionary of the class to
the weight given to the class.
"""
x = numpy.asarray(x)
order = [] # list of (distance, index)
if distance_fn:
for i in range(len(knn.xs)):
dist = distance_fn(x, knn.xs[i])
order.append((dist, i))
else:
# Default: Use a fast implementation of the Euclidean distance
temp = numpy.zeros(len(x))
# Predefining temp allows reuse of this array, making this
# function about twice as fast.
for i in range(len(knn.xs)):
temp[:] = x - knn.xs[i]
dist = numpy.sqrt(numpy.dot(temp,temp))
order.append((dist, i))
order.sort()
# first 'k' are the ones I want.
weights = {} # class -> number of votes
for k in knn.classes:
weights[k] = 0.0
for dist, i in order[:knn.k]:
klass = knn.ys[i]
weights[klass] = weights[klass] + weight_fn(x, knn.xs[i])
return weights
def classify(knn, x, weight_fn=equal_weight, distance_fn=None):
"""classify(knn, x[, weight_fn][, distance_fn]) -> class
Classify an observation into a class. If not specified, weight_fn will
give all neighbors equal weight. distance_fn is an optional function
that takes two points and returns the distance between them. If
distance_fn is None (the default), the Euclidean distance is used.
"""
weights = calculate(
knn, x, weight_fn=weight_fn, distance_fn=distance_fn)
most_class = None
most_weight = None
for klass, weight in weights.items():
if most_class is None or weight > most_weight:
most_class = klass
most_weight = weight
return most_class
关于python - 寻找给定向量的 k 最近邻?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5684370/
在下面的代码中,我得到一个 uninitialized value警告,但仅限于第二个 given/when例子。为什么是这样? #!/usr/bin/env perl use warnings; u
整个“开关”功能是否已成为实验性的?在没有 Perl 的 future 版本破坏我的代码的情况下,我可以依赖其中的某些部分吗?一般来说,将稳定功能更改为实验性的政策是什么? 背景use feature
有没有办法在一个条件语句中写出如下语句? a和b不能同时等于5。 (a可以是5,b可以是5,但是a AND b不能是5) 最佳答案 正如克里斯指出的那样,您要查找的是逻辑异或,相当于逻辑不等于 !=:
我正在寻找一种算法来找到给定 n 条线段的所有交点。以下是来自 http://jeffe.cs.illinois.edu/teaching/373/notes/x06-sweepline.pdf 的伪
数组中有 N 个元素。我可以选择第一项最多 N 次,第二项最多选择 N-1 次,依此类推。 我有 K 个 token 要使用并且需要使用它们以便我可以拥有最大数量的项目。 arr = [3, 4, 8
我正在尝试修复法语文本中的语法性别,想知道是否有办法从某个词条中获取所有单词的列表,以及是否可以在此类列表中进行查找? 最佳答案 尝试: import spacy lemma_lookup = spa
我正在为 Win32 编写一个简单的自动化测试应用程序。它作为一个单独的进程运行,并通过 Windows API 访问目标应用程序。我可以阅读窗口层次结构,查找标签和文本框,并通过发送/发布消息等来单
在 nodeJs 中使用 Sequelize 时,我从 Sequelize 收到此错误,如下所示: { [SequelizeUniqueConstraintError: Validation erro
本文https://arxiv.org/pdf/1703.10757.pdf使用回归激活映射 (RAM) - 而不是类激活映射 (CAM) 来解决问题。有几篇文章描述了如何实现 CAM。但是我找不到
我正在研究 Mach 动态链接器 dyld。这个问题适用于所有 Apple 平台,但很高兴得到特定于平台的答案;我正在使用 ObjC,但如果对你有用的话,我也很乐意翻译 Swift。 The rele
我有一个包含数千个 Instagram 用户 ID 的列表。我如何获得他们的 Instagram 用户名/句柄? 最佳答案 你必须使用这个 Instagram API: https://api.ins
我在下面的代码: def main(args: Array[String]) { val sparkConf = new SparkConf().setAppName("Spark-Hbase").s
我有一个表格,其中包含从 1 到 10 的数字。(从 D2 到 M2) 假设A1中有03/09/2019 并且在B1中有06/09/2019 并且在C1中有Hello 在A 列中,我有多个系列的单词,
我想在给定服务对应的 URI 的情况下检索服务的注释(特别是 @RolesAllowed )。这是一个例子: 服务: @GET @Path("/example") @RolesAllowed({ "B
我看到 OraclePreparedStatementexecuteQuery() 表现出序列化。也就是说,我想使用相同的连接对 Oracle 数据库同时运行两个查询。然而,OraclePrepare
import java.util.Scanner; public class GeometricSumFromK { public static int geometricSum(int k,
我创建了一个抽象基类Page,它说明了如何构建动态网页。我正在尝试想出一种基于作为 HttpServletRequest 传入的 GET 请求生成 Page 的好方法。例如... public cla
我的字符串是一条短信,采用以下两种格式之一: 潜在客户短信: 您已收到 1 条线索 标题:我的领导 潜在客户 ID:12345-2365 警报设置 ID:890 短信回复: 您已收到 1 条回复 标题
我在 python 中有以下代码: class CreateMap: def changeme(listOne, lisrTwo, listThree, listFour, listfive):
这是在 Hibernate 上运行的 JPA2。 我想检索相同实体类型的多个实例,给定它们的 ID。其中许多已经在持久性上下文和/或二级缓存中。 我尝试了几种方法,但似乎都有其缺点: 当我使用 ent
我是一名优秀的程序员,十分优秀!