我在使用 Pymongo 的 find_one 函数时遇到了一个奇怪的问题。我的本地计算机上托管着一个名为“cluster_db”的数据库。它有一个称为“集群”的集合。当我在 mongo shell 中运行查询时,我得到以下输出。
> db
cluster_db
> db.clusters.findOne({_id:-8488068664808428000})
{
"_id" : NumberLong("-8488068664808427924"),
"members" : [
{
"participationCoeff" : 1,
"tweetID" : NumberLong("-8488068664808427924")
}
]
}
>
Run Code Online (Sandbox Code Playgroud)
现在,在代码初始化阶段,我在模块“dbutil”中定义了一个常量,如下所示:
DB_CONNECTION = MongoClient('localhost', 27017)
CLUSTER_DB_HANDLE = DB_CONNECTION['cluster_db']
Run Code Online (Sandbox Code Playgroud)
之后,在一个函数中,我进行以下调用。
dbutil.CLUSTER_DB_HANDLE.clusters.find_one({'_id':clusterID})
Run Code Online (Sandbox Code Playgroud)
但是,上述调用始终返回“None”。如果我转到 MongoShell 并使用相同的 clusterID 运行完全相同的查询,我会看到结果。
我知道这是一个奇怪的错误,但不知何故我无法弄清楚为什么会发生这种情况。在其他地方,我能够使用 dbutil.CLUSTER_DB_HANDLE.clusters 成功调用 cluster_db 中的“集群”集合
运行此代码时出现 [WinError 10057]。而且我不知道为什么当我浏览时它会崩溃,localhost:8081因为相同的代码正在我朋友的机器上运行......
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 8081))
sock.listen(2)
conn, addr = sock.accept()
ans = conn.recv(1024).decode("ascii")
sock.sendall(bytearray("HTTP/1.1 200 ok\n", "ascii"))
sock.sendall(bytearray("\n", "ascii"))
sock.sendall(bytearray("<html>\n<body><h1>Your request</h1><p>Your client sent this request</p><pre>" + ans +"</pre></body></html>", "ascii"))
sock.close()
Run Code Online (Sandbox Code Playgroud)
为什么我收到这个错误?一直在四处寻找,但无法真正找到答案。有什么建议?
使用gridfs-stream,查找和获取文件时如何指定bucket名称?
我的问题是在如何指定 GridFS 存储桶的stackoverflow 上找到的以下问题的后续问题
那里的解决方案提供了一个示例,说明如何在调用 createWriteStream 时指定存储桶。根据@vsivsi 提供的代码,我可以使用以下代码中的“root”选项将文件添加到我的自定义存储桶中:
// fyi, req.file has been populated using multer
var gfs = Grid(mongoose.connection.db);
var writeStream = gfs.createWriteStream({
filename: req.file.originalname,
mode: 'w',
content_type: req.file.mimetype,
root: 'private'
});
Run Code Online (Sandbox Code Playgroud)
这成功地将我的文件添加到 private.files 和 private.chunks。所以现在我想查找并阅读我上传的文件。我的 find() 不使用存储桶,如下所示:
var gfs = Grid(mongoose.connection.db);
gfs.find({
filename: req.params.filename
}).toArray(function(err, files){
// bunch of processing here...
});
Run Code Online (Sandbox Code Playgroud)
现在我如何知道要查询哪个存储桶/根?
我假设在调用 createReadStream() 时我将能够使用相同的“root”选项,但首先我需要找到它。有没有办法告诉 gridfs-stream 使用哪个存储桶/根?
我已经预先清理了数据,下面显示了前4行的格式:
[IN] df.head()
[OUT] Year cleaned
0 1909 acquaint hous receiv follow letter clerk crown...
1 1909 ask secretari state war whether issu statement...
2 1909 i beg present petit sign upward motor car driv...
3 1909 i desir ask secretari state war second lieuten...
4 1909 ask secretari state war whether would introduc...
Run Code Online (Sandbox Code Playgroud)
我已将train_test_split()称为如下:
[IN] X_train, X_test, y_train, y_test = train_test_split(df['cleaned'], df['Year'], random_state=2)
[Note*] `X_train` and `y_train` are now Pandas.core.series.Series of shape (1785,) and `X_test` and `y_test` are also …Run Code Online (Sandbox Code Playgroud) 我想使用VotingClassifier内部 a sklearn Pipeline,在那里我定义了一组分类器 ..
我从这个问题中得到了一些直觉:Using VotingClassifierin Sklearn Pipeline to build the code below,但在这个问题中,每个分类器都在一个独立的管道中定义..我不想以这种方式使用它,我有一个之前准备了一组特征,在具有不同分类器的多管道中重复生成这些特征不是一个好主意(耗时的过程)!
我怎么能做到这一点?!
model = Pipeline([
('feat', FeatureUnion([
('tfidf', TfidfVectorizer(analyzer='char', ngram_range=(3, 5), min_df=0.01, lowercase=True, tokenizer=tokenizeTfidf)),
])),
('pip1', Pipeline([('clf1', GradientBoostingClassifier(n_estimators=1000, random_state=7))])),
('pip2', Pipeline([('clf2', SVC())])),
('pip3', Pipeline([('clf3', RandomForestClassifier())])),
('clf', VotingClassifier(estimators=["pip1", "pip2", "pip3"]))
])
clf = model.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)
但我收到了这个错误:
('clf', VotingClassifier(estimators=["pip1", "pip2", "pip3"])),
File "C:\Python35\lib\site-packages\imblearn\pipeline.py", line 115, in __init__
self._validate_steps()
File "C:\Python35\lib\site-packages\imblearn\pipeline.py", line 139, in _validate_steps
"(but not both) '%s' (type %s) doesn't)" % (t, type(t))) …Run Code Online (Sandbox Code Playgroud) 有兴趣了解如何在 python 中解释 Anderson darling 测试的结果。
似乎 AD 统计数据必须低于其相关显着性水平的临界值,尽管我不确定如何从函数的返回值中正确确定这一点。
这是函数的结果
AndersonResult(statistic=1.383562257554786,
critical_values=array([0.574, 0.654, 0.785, 0.916, 1.089]),
significance_level=array([15. , 10. , 5. , 2.5, 1. ]))
Run Code Online (Sandbox Code Playgroud) 我是 Word2Vec 的新手,我正在尝试根据单词的相似性对单词进行聚类。首先,我使用 nltk 来分隔句子,然后使用生成的句子列表作为 Word2Vec 的输入。然而,当我打印词汇时,它只是一堆字母、数字和符号,而不是单词。具体来说,其中一个字母的示例是“< gensim.models.keyedvectors.Vocab object at 0x00000238145AB438>, 'L':”
# imports needed and logging
import gensim
from gensim.models import word2vec
import logging
import nltk
#nltk.download('punkt')
#nltk.download('averaged_perceptron_tagger')
with open('C:\\Users\\Freddy\\Desktop\\Thesis\\Descriptions.txt','r') as f_open:
text = f_open.read()
arr = []
sentences = nltk.sent_tokenize(text) # this gives a list of sentences
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',level=logging.INFO)
model = word2vec.Word2Vec(sentences, size = 300)
print(model.wv.vocab)
Run Code Online (Sandbox Code Playgroud) 对于给定的二维数组,如下所示,我需要检查所有元素是否小于 0.2。
a = np.array([[0.26002, 0.13918, 0.6008 ],
[0.2997 , 0.28646, 0.41384],
[0.41614, 0.36464, 0.21922]])
Run Code Online (Sandbox Code Playgroud)
这是我的代码,基于这个问题。
res = abs(a<0.2)
all(i==True for i in res)
Run Code Online (Sandbox Code Playgroud)
但是代码抱怨
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud) PEP572中给出的示例之一是
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
Run Code Online (Sandbox Code Playgroud)
目前在 python 中,您必须执行以下操作之一:
# option 1
y = f(x)
[y, y**2, y**3]
Run Code Online (Sandbox Code Playgroud)
或者
# option 2
[f(x), f(x)**2, f(x)**3]
Run Code Online (Sandbox Code Playgroud)
该示例暗示此处的选项 2 可以改进,但我从未见过比第一个选项更推荐的选项。选项 2(以及海象运营商)比选项 1 更好的原因有哪些?
如果我正确理解了concurrent.futuresPython 3 中的模块是如何工作的,则以下代码:
import concurrent.futures
import threading
# Simple function returning a value
def test(i):
a = 'Hello World\n'
return a
def main():
output1 = list()
with concurrent.futures.ThreadPoolExecutor() as executor:
# psdd iterator to test function
for out1 in executor.map(test, range(0, 10)):
# append returned result
output1.append(out1)
# confirm output
print(output1)
print("Task Executed {}".format(threading.current_thread()))
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
...执行以下功能:
test()。然而,我真正想要的是在我的函数中并行处理循环,main()如下所示:
import concurrent.futures
import threading
def main():
output1 = …Run Code Online (Sandbox Code Playgroud) python ×7
python-3.x ×3
imblearn ×2
mongodb ×2
scikit-learn ×2
bucket ×1
gensim ×1
gridfs ×1
javascript ×1
knn ×1
numpy ×1
oversampling ×1
pep ×1
pymongo ×1
python-3.8 ×1
scipy ×1
scipy.stats ×1
sockets ×1
statistics ×1
tf-idf ×1
tokenize ×1
word2vec ×1