- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在创建句子的词袋表示。然后将句子中存在的单词与文件“vectors.txt”进行比较,以获得它们的嵌入向量。在获得句子中存在的每个单词的向量后,我将取句子中单词向量的平均值。这是我的代码:
import nltk
import numpy as np
from nltk import FreqDist
from nltk.corpus import brown
news = brown.words(categories='news')
news_sents = brown.sents(categories='news')
fdist = FreqDist(w.lower() for w in news)
vocabulary = [word for word, _ in fdist.most_common(10)]
num_sents = len(news_sents)
def averageEmbeddings(sentenceTokens, embeddingLookupTable):
listOfEmb=[]
for token in sentenceTokens:
embedding = embeddingLookupTable[token]
listOfEmb.append(embedding)
return sum(np.asarray(listOfEmb)) / float(len(listOfEmb))
embeddingVectors = {}
with open("D:\\Embedding\\vectors.txt") as file:
for line in file:
(key, *val) = line.split()
embeddingVectors[key] = val
for i in range(num_sents):
features = {}
for word in vocabulary:
features[word] = int(word in news_sents[i])
print(features)
print(list(features.values()))
sentenceTokens = []
for key, value in features.items():
if value == 1:
sentenceTokens.append(key)
sentenceTokens.remove(".")
print(sentenceTokens)
print(averageEmbeddings(sentenceTokens, embeddingVectors))
print(features.keys())
不知道为什么,但我得到了这个错误:
TypeError Traceback (most recent call last)
<ipython-input-4-643ccd012438> in <module>()
39 sentenceTokens.remove(".")
40 print(sentenceTokens)
---> 41 print(averageEmbeddings(sentenceTokens, embeddingVectors))
42
43 print(features.keys())
<ipython-input-4-643ccd012438> in averageEmbeddings(sentenceTokens, embeddingLookupTable)
18 listOfEmb.append(embedding)
19
---> 20 return sum(np.asarray(listOfEmb)) / float(len(listOfEmb))
21
22 embeddingVectors = {}
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U9') dtype('<U9') dtype('<U9')
附:嵌入向量看起来像:
the 0.011384 0.010512 -0.008450 -0.007628 0.000360 -0.010121 0.004674 -0.000076
of 0.002954 0.004546 0.005513 -0.004026 0.002296 -0.016979 -0.011469 -0.009159
and 0.004691 -0.012989 -0.003122 0.004786 -0.002907 0.000526 -0.006146 -0.003058
one 0.014722 -0.000810 0.003737 -0.001110 -0.011229 0.001577 -0.007403 -0.005355
in -0.001046 -0.008302 0.010973 0.009608 0.009494 -0.008253 0.001744 0.003263
使用 np.sum 后出现此错误:
TypeError Traceback (most recent call last)
<ipython-input-13-8a7edbb9d946> in <module>()
40 sentenceTokens.remove(".")
41 print(sentenceTokens)
---> 42 print(averageEmbeddings(sentenceTokens, embeddingVectors))
43
44 print(features.keys())
<ipython-input-13-8a7edbb9d946> in averageEmbeddings(sentenceTokens, embeddingLookupTable)
18 listOfEmb.append(embedding)
19
---> 20 return np.sum(np.asarray(listOfEmb)) / float(len(listOfEmb))
21
22 embeddingVectors = {}
C:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in sum(a, axis, dtype, out, keepdims)
1829 else:
1830 return _methods._sum(a, axis=axis, dtype=dtype,
-> 1831 out=out, keepdims=keepdims)
1832
1833
C:\Anaconda3\lib\site-packages\numpy\core\_methods.py in _sum(a, axis, dtype, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
---> 32 return umr_sum(a, axis, dtype, out, keepdims)
33
34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: cannot perform reduce with flexible type
最佳答案
你有一个 numpy 字符串数组,而不是 float 。这就是 dtype('<U9')
的意思。 -- 一个小端编码的 unicode 字符串,最多 9 个字符。
尝试:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
但是,这里根本不需要 numpy。你真的可以这样做:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
或者如果你真的打算使用 numpy。
return np.asarray(listOfEmb, dtype=float).mean()
关于python - 类型错误 : ufunc 'add' did not contain a loop with signature matching types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35013726/
大家好,所有rdf/sparql开发人员。这是一个困扰了我一段时间的问题,但是自从发布rdf和sparql规范以来,似乎没人能准确回答这个问题。 为了说明这种情况,RDF定义了几种方法来处理资源的多值
我在我的应用程序中使用 Bootstrap ,现在遇到了一个大问题。问题是 .container 元素在 1360 px 的屏幕上具有 274px 的左右边距,这是相当大的。结果,一切看起来都被挤到了
我在删除Docker容器时遇到问题-当我使用前一个命令时,它不起作用(Docker报告了容器ID,但没有删除它)。后者起作用了。据我所知,Docker语法是相同的: C:\Users\user>doc
std::back_inserter 仅适用于带有 push_back 的容器,因此它不适用于 set 和 map 另一方面,std::inserter 适用于所有容器类型。那么我可以一直使用 std
我正在开发 Spring Boot + Redis 示例。在此示例中,我开发了一些自定义方法,这些方法基于 RoleName 提取详细信息。对于以下方法 userRepository.findByRo
在我的 Swift 应用程序中尝试实现 Google Tag Manager v5 时,我遇到了以下警告,这给我带来了一些麻烦: GoogleTagManager warning: No defaul
安装了新的 Laravel 8 项目并在加载第一个实例时,出现以下错误。这很奇怪,因为我把它放在一边,后来从 Laravel 5.8 -> 6 升级了另一个项目(工作正常),当我去检查网站时遇到了类似
我有以下测试代码,它只创建一个空的 hashmap (containers.map) 并在之后填充它: hashtable = containers.Map('KeyType','char','Va
我对它们之间的差异有一点了解,但是拥有专家意见将是很棒的。 Container-Optimized Google Compute Engine Images Google Container Engi
我会模板化一个函数,以便将它与 vector、set 或任何其他 STL 容器(具有正确的 API...)一起使用 我的函数当前原型(prototype)是: vector> f ( const ve
我正在尝试匹配包含和不包含某些字符串的 Pandas DataFrame 的行。例如: import pandas df = pandas.Series(['ab1', 'ab2', 'b2', 'c
我需要在一个非常庞大的全文索引数据库中找到一些文本,但我不知道在我的查询术语变体中使用什么更好。 我看过一些使用的例子 SELECT Foo.Bar FROM Foo WHERE
Traceback (most recent call last): File "demo.py", line 132, in `result = find_strawberry(image
我正在尝试编写一个函数,其中一列包含一个子字符串并且不包含另一个子字符串。 在下面的示例中,如果我的行包含“某些项目”并且不包含“开销”,我希望我的函数返回 1。 row| example strin
我试图在文本文件中 append 包含给定字符串集的任何行。我创建了一个测试文件,在其中放置了这些字符串之一。我的代码应该将文本文件中包含这些字符串之一的任何行打印在与文本文件中的上一行相同的行上。这
我正在尝试学习如何使用 std.container 中可用的各种容器结构,但我无法理解如何执行以下操作: 1) 如何创建一个空容器?例如,假设我有一个用户定义的类 Foo,并且想要创建一个应该包含 F
$contains: [1, 2] // @> [1, 2] (PG array contains operator) $contained: [1, 2] // <@ [1,
我看到 CSS 中使用了这种“div#container”语法,我想知道它是如何工作的。有人有它的资源吗? 最佳答案 除了作为上面提到的唯一引用之外,ID 还增加了特异性(我强烈建议您阅读这篇文章或一
我有一个生成很多子对象的应用程序,每个子对象都与一些全局应用程序对象一起工作,例如在全局应用程序注册表中注册自己,更新应用程序统计信息等。 应用程序应该如何将访问这些全局对象的能力传递给 child
Here is a Sencha fiddle of my tab panel setup.按钮被动态添加到 vbox 选项卡容器中,该容器是 hbox 布局设置的一部分。选项卡容器的宽度由 flex
我是一名优秀的程序员,十分优秀!