我是python新手,需要帮助!我正在练习python NLTK文本分类.以下是我在http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/上练习的代码示例
我试过这个
from nltk import bigrams
from nltk.probability import ELEProbDist, FreqDist
from nltk import NaiveBayesClassifier
from collections import defaultdict
train_samples = {}
with file ('positive.txt', 'rt') as f:
for line in f.readlines():
train_samples[line]='pos'
with file ('negative.txt', 'rt') as d:
for line in d.readlines():
train_samples[line]='neg'
f=open("test.txt", "r")
test_samples=f.readlines()
def bigramReturner(text):
tweetString = text.lower()
bigramFeatureVector = {}
for item in bigrams(tweetString.split()):
bigramFeatureVector.append(' '.join(item))
return bigramFeatureVector
def get_labeled_features(samples):
word_freqs = {}
for text, label in train_samples.items():
tokens = text.split()
for …Run Code Online (Sandbox Code Playgroud) 我正在使用Python 3.5,使用Anaconda进行安装和管理.我想使用一些文本训练NGramModel(来自nltk).我的安装找不到模块nltk.model
这个问题有一些可能的答案(选择正确的答案,并解释如何做到这一点):
鉴于big.txt来自norvig.com/big.txt,我们的目标是快速计算双子座(想象一下,我必须重复这次计数100,000次).
根据python中的Fast/Optimize N-gram实现,像这样提取bigrams是最优的:
_bigrams = zip(*[text[i:] for i in range(2)])
Run Code Online (Sandbox Code Playgroud)
如果我正在使用Python3,生成器将不会被评估,直到我实现它list(_bigrams)或其他一些将执行相同的功能.
import io
from collections import Counter
import time
with io.open('big.txt', 'r', encoding='utf8') as fin:
text = fin.read().lower().replace(u' ', u"\uE000")
while True:
_bigrams = zip(*[text[i:] for i in range(2)])
start = time.time()
top100 = Counter(_bigrams).most_common(100)
# Do some manipulation to text and repeat the counting.
text = manipulate(text, top100)
Run Code Online (Sandbox Code Playgroud)
但是每次迭代需要大约1秒以上,100,000次迭代会太长.
我也尝试过sklearnCountVectorizer,但是提取,计算和获得top100双字母的时间与原生python相当.
然后我尝试了一些multiprocessing,使用Python多处理和共享计数器的轻微修改和 …
最近维基百科故意破坏检测竞赛的获胜者建议通过" 检测考虑QWERTY键盘布局的随机键盘命中 "来改善检测.
例: woijf qoeoifwjf oiiwjf oiwj pfowjfoiwjfo oiwjfoewoh
是否有任何软件可以执行此操作(最好是免费和开源)?
如果没有,是否有一个活跃的FOSS项目,其目标是实现这一目标?
如果没有,您会如何建议实施此类软件?
我试图在scala中基于n-gram编写分离的印刷算法.如何为大文件生成n-gram:例如,对于包含"蜜蜂是蜜蜂的蜜蜂"的文件.
你能给我一些提示怎么做吗?抱歉给你带来不便.
至少可以考虑使用3种类型的n-gram来表示文本文档:
我不清楚哪一个应该用于给定的任务(聚类,分类等).我在某处读到,当文字包含拼写错误时,字符级别的n-gram优于字级n-gram,因此"Mary loves dogs"仍然类似于"Mary lpves dogs".
选择"正确"表示还有其他标准需要考虑吗?
我试图计算我所拥有的数据的困惑.我使用的代码是:
import sys
sys.path.append("/usr/local/anaconda/lib/python2.7/site-packages/nltk")
from nltk.corpus import brown
from nltk.model import NgramModel
from nltk.probability import LidstoneProbDist, WittenBellProbDist
estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
lm = NgramModel(3, brown.words(categories='news'), True, False, estimator)
print lm
Run Code Online (Sandbox Code Playgroud)
但我收到错误,
File "/usr/local/anaconda/lib/python2.7/site-packages/nltk/model/ngram.py", line 107, in __init__
cfd[context][token] += 1
TypeError: 'int' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)
我已经为我的数据执行了潜在Dirichlet分配,并且我已经生成了unigrams及其各自的概率(它们被归一化为数据的总概率之和为1).
我的unigrams和他们的概率看起来像:
Negroponte 1.22948976891e-05
Andreas 7.11290670484e-07
Rheinberg 7.08255885794e-07
Joji 4.48481435106e-07
Helguson 1.89936727391e-07
CAPTION_spot 2.37395965468e-06
Mortimer 1.48540253778e-07
yellow 1.26582575863e-05
Sugar 1.49563800878e-06
four 0.000207196011781
Run Code Online (Sandbox Code Playgroud)
这只是我所拥有的unigrams文件的一个片段.对于大约1000行,遵循相同的格式.总概率(第二列)求和1.
我是一个崭露头角的程序员.这个ngram.py属于nltk包,我很困惑如何纠正这个问题.我这里的示例代码来自nltk文档,我现在不知道该怎么做.请帮忙我能做些什么.提前致谢!
可以在Keras中使用n-gram吗?
例如,句子在X_train数据帧中包含"句子"列.
我以下列方式使用Keras的tokenizer:
tokenizer = Tokenizer(lower=True, split=' ')
tokenizer.fit_on_texts(X_train.sentences)
X_train_tokenized = tokenizer.texts_to_sequences(X_train.sentences)
Run Code Online (Sandbox Code Playgroud)
然后我填写句子:
X_train_sequence = sequence.pad_sequences(X_train_tokenized)
Run Code Online (Sandbox Code Playgroud)
我还使用一个简单的LSTM网络:
model = Sequential()
model.add(Embedding(MAX_FEATURES, 128))
model.add(LSTM(32, dropout=0.2, recurrent_dropout=0.2,
activation='tanh', return_sequences=True))
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2, activation='tanh'))
model.add(Dense(number_classes, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)
在这种情况下,tokenizer执行.在Keras docs:https://keras.io/preprocessing/text/ 我看到字符处理是可能的,但这不适合我的情况.
我的主要问题:我可以将n-gram用于NLP任务(不仅仅是情感分析,而是任何NLP任务)
澄清一下:我不仅要考虑单词而且要考虑单词组合.我想尝试看看它是否有助于模拟我的任务.
是否有可能告诉ElasticSearch使用所有克的"最佳匹配"而不是使用克作为同义词?
默认情况下,ElasticSearch使用gram作为同义词并返回不匹配的文档.最好以示例的方式展示,假设我们在索引中有两个人:
alice wang
sarah kerry
Run Code Online (Sandbox Code Playgroud)
我们搜索ali12345:
{
query: {
bool: {
should: {
match: { name: 'ali12345' }
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它会回来的alice wang.
这怎么可能?因为默认情况下ElasticSearch使用gram作为同义词,因此,即使只有一克匹配 - 文档也会匹配.
如果您检查查询,您会看到它将克视为同义词
...
"explanation": {
"value": 5.274891,
"description": "weight(Synonym(name: ali name:li1 name:i12 name:123 name:234 name:345 ) in 0) [PerFieldSimilarity], result of:",
...
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能告诉它使用"最佳匹配"查询,以达到如下目的:
{
query: {
bool: {
should: [
{ term: { body: 'ali' }},
{ term: { body: 'li1' }},
{ term: { body: 'i12' …Run Code Online (Sandbox Code Playgroud) 我使用 utf8mb4_bin 作为标题列,所以我希望它是全文区分大小写的搜索。但实际上查询返回空。
CREATE TABLE `test_table` (
`id` int NOT NULL AUTO_INCREMENT,
`title` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `title` (`title`) WITH parser ngram) ENGINE=InnoDB AUTO_INCREMENT=173 DEFAULT
CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
INSERT INTO test_table value (NULL, 'Hello');
SELECT *
FROM test_table
WHERE match(title) against ('Hello' in boolean MODE) > 0; // return empty
Run Code Online (Sandbox Code Playgroud)
但如果我插入并查询“hello”,它会起作用,ngram 解析器是否会尝试小写来查询术语?
n-gram ×10
nlp ×3
nltk ×3
python ×3
algorithm ×1
counter ×1
data-mining ×1
keras ×1
mapreduce ×1
mysql ×1
optimization ×1
python-2.7 ×1
python-3.x ×1
qwerty ×1
scala ×1
text-mining ×1
tokenize ×1
trigram ×1
uppercase ×1