小编sop*_*ros的帖子

PyMongo find_one 不返回现有条目

我在使用 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 中的“集群”集合

python mongodb pymongo

2
推荐指数
1
解决办法
3442
查看次数

Python 套接字 [WinError 10057]?

运行此代码时出现 [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)

为什么我收到这个错误?一直在四处寻找,但无法真正找到答案。有什么建议?

python sockets python-3.x

2
推荐指数
1
解决办法
1万
查看次数

使用 gridfs-stream 执行 find() 时如何指定 GridFS 存储桶

使用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 使用哪个存储桶/根?

javascript bucket mongodb gridfs gridfs-stream

2
推荐指数
1
解决办法
1735
查看次数

SMOTE初始化期望n_neighbors &lt;= n_samples,但n_samples &lt;n_neighbors

我已经预先清理了数据,下面显示了前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)

tf-idf knn scikit-learn oversampling imblearn

2
推荐指数
2
解决办法
4977
查看次数

将 VotingClassifier 与 Sklearn 管道内的其他分类器一起使用

我想使用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 machine-learning scikit-learn imblearn

2
推荐指数
1
解决办法
884
查看次数

解释安德森亲爱的测试 scipy

有兴趣了解如何在 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)

python statistics scipy statistical-test scipy.stats

2
推荐指数
1
解决办法
4169
查看次数

Word2Vec 词汇结果仅包含字母和符号

我是 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)

python tokenize python-3.x gensim word2vec

2
推荐指数
1
解决办法
2524
查看次数

检查 NumPy 数组的所有元素是否符合条件

对于给定的二维数组,如下所示,我需要检查所有元素是否小于 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)

python numpy conditional-statements

2
推荐指数
1
解决办法
4035
查看次数

PEP572 中的海象运算符示例

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 更好的原因有哪些?

python pep python-3.8

2
推荐指数
1
解决办法
408
查看次数

Python 3并发.futures - 并行处理for循环

如果我正确理解了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)

...执行以下功能:

  1. 将 for 循环传递给名为 的函数test()
  2. 并行处理循环,而不是串行处理。

然而,我真正想要的是在我的函数中并行处理循环,main()如下所示:

import concurrent.futures
import threading


def main():
    output1 = …
Run Code Online (Sandbox Code Playgroud)

python-3.x concurrent.futures

2
推荐指数
1
解决办法
1万
查看次数