text stringlengths 0 27.6k | python int64 0 1 | DeepLearning or NLP int64 0 1 | Other int64 0 1 | Machine Learning int64 0 1 | Mathematics int64 0 1 | Trash int64 0 1 |
|---|---|---|---|---|---|---|
I'm relatively new to Python NLP and I am trying to process a CSV file with SpaCy. I'm able to load the file just fine using Pandas, but when I attempt to process it with SpaCy's nlp function, the compiler errors out approximately 5% of the way through the file's contents.
Code block follows:
import pandas as pd
df = pd.read_csv('./reviews.washington.dc.csv')
import spacy
nlp = spacy.load('en')
for parsed_doc in nlp.pipe(iter(df['comments']), batch_size=1, n_threads=4):
print (parsed_doc.text)
I've also tried:
df['parsed'] = df['comments'].apply(nlp)
with the same result.
The traceback I'm receiving is:
Traceback (most recent call last):
File "/Users/john/Downloads/spacy_load.py", line 11, in <module>
for parsed_doc in nlp.pipe(iter(df['comments']), batch_size=1,
n_threads=4):
File "/usr/local/lib/python3.6/site-packages/spacy/language.py",
line 352, in pipe for doc in stream:
File "spacy/syntax/parser.pyx", line 239, in pipe
(spacy/syntax/parser.cpp:8912)
File "spacy/matcher.pyx", line 465, in pipe (spacy/matcher.cpp:9904)
File "spacy/syntax/parser.pyx", line 239, in pipe (spacy/syntax/parser.cpp:8912)
File "spacy/tagger.pyx", line 231, in pipe (spacy/tagger.cpp:6548)
File "/usr/local/lib/python3.6/site-packages/spacy/language.py", line 345,
in <genexpr> stream = (self.make_doc(text) for text in texts)
File "/usr/local/lib/python3.6/site-packages/spacy/language.py", line 293,
in <lambda> self.make_doc = lambda text: self.tokenizer(text)
TypeError: Argument 'string' has incorrect type (expected str, got float)
Can anyone shed some light on why this is happening, as well as how I might work around it? I've tried various workarounds from the site to no avail. Try/except blocks have had no effect, either.
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm trying to use the Stanford Parser through NLTK, following the example here.
I follow the first two lines of the example (with the necessary import)
from nltk.parse.corenlp import CoreNLPDependencyParser
dep_parser = CoreNLPDependencyParser(url='http://localhost:9000')
parse, = dep_parser.raw_parse('The quick brown fox jumps over the lazy dog.')
but I get an error saying:
[...] Failed to establish a new connection: [Errno 61] Connection refused"
I realize that it must be an issue with trying to connect to the url given as input to the constructor.
dep_parser = CoreNLPDependencyParser(url='http://localhost:9000')
What url should I be connecting to, if not this? If this is correct, what is the issue?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am developing a Python program in order to find the etymology of words in a text. I have found out there are basically two options: parsing an online dictionary that provides etymology or using an API. I found this reply here but I don't seem to understand how to link the Oxford API with my Python program.
Can anyone explain me how to look up a word in an english dictionary? Thank you in advance.
Link to the question here
Note that while WordNet does not have all English words, what about the Oxford English Dictionary? (http://developer.oxforddictionaries.com/). Depending on the scope of your project, it could be a killer API.
Have you tried looking at Grady Ward's Moby? [link] (http://icon.shef.ac.uk/Moby/).
You could add it as a lexicon in NLTK (see notes on "Loading your own corpus" in Section 2.1).
from nltk.corpus import PlaintextCorpusReader
corpus_root = '/usr/share/dict'
wordlists = PlaintextCorpusReader(corpus_root, '.*')
from nltk.corpus import BracketParseCorpusReader
corpus_root = r"C:\corpora\penntreebank\parsed\mrg\wsj"
file_pattern = r".*/wsj_.*\.mrg"
ptb = BracketParseCorpusReader(corpus_root, file_pattern)
| 1 | 1 | 0 | 0 | 0 | 0 |
My problem is basically as follows. I have a pandas dataframe, with a column which contains fairly large amounts of text (generally 20 to 200 words). This dataframe is about 600k rows. On top of that I have a list of words, which is about 150k items long, which need to be filtered out of the strings in the dataframe. I am currently using this method to do this:
for word in uncommon_words:
reports['Report_Clean_Filtered'] = reports['Report_Clean'].str.replace(word, '')
Where uncommon_words is the list of words and reports is the dataframe.
My estimation is that this will take around 27 hours on my machine. Is there a better (or at least faster) way to do this? I have a very open mind! :)
| 1 | 1 | 0 | 0 | 0 | 0 |
I am working on an image captioning system in python using Keras and when using argmax search I get reasonable results (~0.58 Bleu_1 score and the sentences are quite diverse).
When I try beam search, however, I get almost the same sentence for every image.
I have the following code for generating the captions:
# create an array of captions for a chunk of images; first token
# of each caption is the start token
test_x = np.zeros((chunk_size, self.max_len - 1), dtype=np.int)
test_x[:, 0] = self.start_idx + 1
# probability of each caption is 1
captions_probs = np.ones(chunk_size)
# for every image, maintain a heap with the best captions
self.best_captions = [FixedCapacityMaxHeap(20) for i in range(chunk_size)]
# call beam search using the current cnn features
self.beam_search(cnn_feats, test_x, captions_probs, 0, beam_size)
The beam search method is the following:
def beam_search(self, cnn_feats, generated_captions, captions_probs, t, beam_size):
# base case: the generated captions have max_len length, so
# we can remove the (zero) pad at the end and for each image
# we can insert the generated caption and its probablity into
# the heap with the best captions
if t == self.max_len - 1:
for i in range(len(generated_captions)):
caption = self.remove_zero_pad(list(generated_captions[i]))
self.best_captions[i].push(list(caption), captions_probs[i])
else:
# otherwise, make a prediction (we only keep the element at time
# step t + 1, as the LSTM has a many-to-many architecture, but we
# are only interested in the next token (for each image).
pred = self.model.predict(x=[cnn_feats, generated_captions],
batch_size=128,
verbose=1)[:, t + 1, :]
# efficiently get the indices of the tokens with the greatest probability
# for each image (they are not necessarily sorted)
top_idx = np.argpartition(-pred, range(beam_size), axis=1)[:, :beam_size]
# store the probability of those tokens
top_probs = pred[np.arange(top_idx.shape[0])[:, None], top_idx]
# for every 'neighbour' (set of newly generated tokens for every image)
# get the indices of these tokens, add them to the current captions and
# update the captions probabilities by multiplying them with the probabilities
# of the current tokens, then recursively call beam_search
for i in range(beam_size):
curr_idx = top_idx[:, i]
generated_captions[:, t + 1] = curr_idx
curr_captions_probs = top_probs[:, i] * captions_probs
self.beam_search(cnn_feats, generated_captions, curr_captions_probs, t+1, beam_size)
The FixedCapacityHeap I am using is:
class FixedCapacityMaxHeap(object):
def __init__(self, capacity):
self.capacity = capacity
self.h = []
def push(self, value, priority):
if len(self.h) < self.capacity:
heapq.heappush(self.h, (priority, value))
else:
heapq.heappushpop(self.h, (priority, value))
def pop(self):
if len(self.h) >= 0:
return heapq.nlargest(1, self.h)[0]
else:
return None
The problem is that the captions generated using beam search are almost the same for every image (eg: 'scaling a in on', 'scaling a are in in of'', 'scaling a are in'), while the argmax version (just taking the token with the highest probability at each time step) is capable of actually producing good captions. I have been stuck on this for quite a long time now. I have tried a different implementation (computing the caption for each image with a beam_seach call instead of computing all of them at once) and I have also experimented with the softmax temperature parameter (which is responsible for how confident the LSTM is in its predictions), but none of these seems to solve the problem, so any idea is appreciated.
| 1 | 1 | 0 | 1 | 0 | 0 |
I'm using Google's Word2vec and I'm wondering how to get the top words that are predicted by a skipgram model that is trained using hierarchical softmax, given an input word?
For instance, when using negative sampling, one can simply multiply an input word's embedding (from the input matrix) with each of the vectors in the output matrix and take the one with the top value. However, in hierarchical softmax, there are multiple output vectors that correspond to each input word, due to the use of the Huffman tree.
How do we compute the likelihood value/probability of an output word given an input word in this case?
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm training my own word2vec model using different data. To implement the resulting model into my classifier and compare the results with the original pre-trained Word2vec model I need to save the model in binary extension .bin. Here is my code, sentences is a list of short messages.
import gensim, logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = gensim.models.word2vec.LineSentence('dati.txt')
model = gensim.models.Word2Vec(
sentences, size=300, window=5, min_count=5, workers=5,
sg=1, hs=1, negative=0
)
model.save_word2vec_format('model.bin', binary=True)
The last method, save_word2vec_format, gives me this error:
AttributeError: 'Word2Vec' object has no attribute 'save_word2vec_format'
What am I missing here? I've read the documentation of gensim and other forums. This repo on github uses almost the same configuration so I cannot understand what's wrong. I've tried to switch from skipgram to cbow and from hierarchical softmax to negative sampling with no results.
Thank you in advance!
| 1 | 1 | 0 | 0 | 0 | 0 |
Example:
I have a sentence 'Face book is a social networking company', which I want to clean by concatenating 'Face' and 'book' into 'Facebook'. I would like to check and perform this for numerous sentences. Any suggestions on how can I do this?
I thought of something on the lines of this: first tokenzing the sentence and then looping over every word and check if the token (word) after 'face' is 'book' and then delete the two elements and all 'Facebook'.
| 1 | 1 | 0 | 0 | 0 | 0 |
I using Twint to extract tweets resulted from a particular search (that gives me about 100k tweets).
The problem is that Twint outputs the tweet content with the emoji title and not its specific unicode. This is one example:
@LulapeloBrasil presidente minha eterna gratidão a tudo que senhor fez, faz e fará ao nosso povo. Seguiremos lutando pelos nossos ideais! <Emoji: Heavy red heart> <Emoji: Flexed biceps (dark skin tone)> #LulaLivre #EusouLula #LulaValeALuta #OcupaSaoBernardo
This is bad because I want to tokenize the tweet for further analysis (e.g. emoji usage) and a traditional tweet tokenizer (e.g. nltk TweetTokenizer) won't tokenize properly.
Do you have any suggestion about how can I convert these emojis titles to their respective unicode (I'm able to extract the titles only using re)?
Where can I get the data that emojepedia uses? Or where can I download a list of all twitter emojis containing their unicode code and titles?
| 1 | 1 | 0 | 0 | 0 | 0 |
I wanted to learn more about NLP. I came across this piece of code. But I was confused about the outcome of TfidfVectorizer.fit_transform when the result is printed. I am familiar with what tfidf is but I could not understand what the numbers mean.
import tensorflow as tf
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import os
import io
import string
import requests
import csv
import nltk
from zipfile import ZipFile
sess = tf.Session()
batch_size = 100
max_features = 1000
save_file_name = os.path.join('smsspamcollection', 'SMSSpamCollection.csv')
if os.path.isfile(save_file_name):
text_data = []
with open(save_file_name, 'r') as temp_output_file:
reader = csv.reader(temp_output_file)
for row in reader:
text_data.append(row)
else:
zip_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip'
r = requests.get(zip_url)
z = ZipFile(io.BytesIO(r.content))
file = z.read('SMSSpamCollection')
# Format data
text_data = file.decode()
text_data = text_data.encode('ascii', errors='ignore')
text_data = text_data.decode().split('
')
text_data = [x.split('\t') for x in text_data if len(x) >= 1]
# And write to csv
with open(save_file_name, 'w') as temp_output_file:
writer = csv.writer(temp_output_file)
writer.writerows(text_data)
texts = [x[1] for x in text_data]
target = [x[0] for x in text_data]
target = [1 if x == 'spam' else 0 for x in target]
# Normalize the text
texts = [x.lower() for x in texts] # lower
texts = [''.join(c for c in x if c not in string.punctuation) for x in texts] # remove punctuation
texts = [''.join(c for c in x if c not in '0123456789') for x in texts] # remove numbers
texts = [' '.join(x.split()) for x in texts] # trim extra whitespace
def tokenizer(text):
words = nltk.word_tokenize(text)
return words
tfidf = TfidfVectorizer(tokenizer=tokenizer, stop_words='english', max_features=max_features)
sparse_tfidf_texts = tfidf.fit_transform(texts)
print(sparse_tfidf_texts)
And the output is:
(0, 630) 0.37172623140154337 (0, 160) 0.36805562944957004 (0,
38) 0.3613966215413548 (0, 545) 0.2561101665717327 (0,
326) 0.2645280991765623 (0, 967) 0.3277447602873963 (0,
421) 0.3896274380321477 (0, 227) 0.28102915589024796 (0,
323) 0.22032541100275282 (0, 922) 0.2709848154866997 (1,
577) 0.4007895093299793 (1, 425) 0.5970064521899725 (1,
943) 0.6310763941180291 (1, 878) 0.29102173465492637 (2,
282) 0.1771481430848552 (2, 243) 0.5517018054305785 (2,
955) 0.2920174942032025 (2, 138) 0.30143666813167863 (2,
946) 0.2269933441326121 (2, 165) 0.3051095293405041 (2,
268) 0.2820392223588522 (2, 780) 0.24119626642264894 (2,
823) 0.1890454397278538 (2, 674) 0.256251970757827 (2,
874) 0.19343834015314287 : : (5569, 648) 0.24171652492226922
(5569, 123) 0.23011909339432202 (5569, 957) 0.24817919217662862
(5569, 549) 0.28583789844730134 (5569, 863) 0.3026729783085827
(5569, 844) 0.20228305447951195 (5569, 146) 0.2514415602877767
(5569, 595) 0.2463259875380789 (5569, 511) 0.3091904754885042
(5569, 230) 0.2872728684768659 (5569, 638) 0.34151390143548765
(5569, 83) 0.3464271621701711 (5570, 370) 0.4199910200421362
(5570, 46) 0.48234172093857797 (5570, 317) 0.4171646676697801
(5570, 281) 0.6456993475093024 (5572, 282) 0.25540827228532487
(5572, 385) 0.36945842040023935 (5572, 448) 0.25540827228532487
(5572, 931) 0.3031800542518209 (5572, 192) 0.29866989620926737
(5572, 303) 0.43990016711221736 (5572, 87) 0.45211284173737176
(5572, 332) 0.3924202767503492 (5573, 866) 1.0
I would be more than happy if someone can explain about the output.
| 1 | 1 | 0 | 0 | 0 | 0 |
I am working on text classification task where my dataset contains a lot of abbreviations and proper nouns. For instance: Milka choc. bar.
My idea is to use bidirectional LSTM model with word2vec embedding.
And here is my problem how to code words, that not appears in the dictionary?
I partially solved this problem by merging pre-trained vectors with randomly initialized. Here is my implementation:
import gensim
from gensim.models import Word2Vec
from gensim.utils import simple_preprocess
from gensim.models.keyedvectors import KeyedVectors
word_vectors = KeyedVectors.load_word2vec_format('ru.vec', binary=False, unicode_errors='ignore')
EMBEDDING_DIM=300
vocabulary_size=min(len(word_index)+1,num_words)
embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM))
for word, i in word_index.items():
if i>=num_words:
continue
try:
embedding_vector = word_vectors[word]
embedding_matrix[i] = embedding_vector
except KeyError:
embedding_matrix[i]=np.random.normal(0,np.sqrt(0.25),EMBEDDING_DIM)
def LSTMModel(X,words_nb, embed_dim, num_classes):
_input = Input(shape=(X.shape[1],))
X = embedding_layer = Embedding(words_nb,
embed_dim,
weights=[embedding_matrix],
trainable=True)(_input)
X = The_rest_of__the_LSTM_model()(X)
Do you think, that allowing the model to adjust the embedding weights is a good idea?
Could you please tell me, how can I encode words like choc? Obviously, this abbreviation stands for chocolate.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have been stuck trying to get the Stanford POS Tagger to work for a while. From an old SO post I found the following (slightly modified) code:
stanford_dir = 'C:/Users/.../stanford-postagger-2017-06-09/'
from nltk.tag import StanfordPOSTagger
#from nltk.tag.stanford import StanfordPOSTagger # I tried it both ways
from nltk import word_tokenize
# Add the jar and model via their path (instead of setting environment variables):
jar = stanford_dir + 'stanford-postagger.jar'
model = stanford_dir + 'models/english-left3words-distsim.tagger'
pos_tagger = StanfordPOSTagger(model, jar, encoding='utf8')
text = pos_tagger.tag(word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
However, I get the following error:
LookupError:
===========================================================================
NLTK was unable to find the java file!
Use software specific configuration paramaters or set the JAVAHOME environment variable.
===========================================================================
I don't know what java file it is talking about. I'm sure it's finding the right files because if I change the path to something incorrect I get a different error:
LookupError: Could not find stanford-postagger.jar jar file at C:/Users/.../stanford-postagger-2017-06-09/sstanford-postagger.jar
What java file is missing? How do I get the Stanford POS tagger to work?
EDIT:
I went to this link for Stanford NLP on Windows and tried:
(Second EDIT - adding the installation procedures):
import urllib.request
import zipfile
urllib.request.urlretrieve(r'http://nlp.stanford.edu/software/stanford-postagger-full-2015-04-20.zip', r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20.zip')
zfile = zipfile.ZipFile(r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20.zip')
zfile.extractall(r'C:/Users/HMISYS/Downloads/')
# End second edit
from nltk.tag.stanford import StanfordPOSTagger
# Trying on an older version
_model_filename = r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20/models/english-bidirectional-distsim.tagger'
_path_to_jar = r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20/stanford-postagger.jar'
st = StanfordPOSTagger(model_filename=_model_filename, path_to_jar=_path_to_jar)
text = st.tag(nltk.word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
but I got the same error. Based on this post I set my path variables with the following:
set STANFORDTOOLSDIR=$HOME
set CLASSPATH=$STANFORDTOOLSDIR/stanford-postagger-full-2015-04-20/stanford-postagger.jar
set export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-postagger-full-2015-04-20/models
But I get this error:
NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH environment variable.
| 1 | 1 | 0 | 0 | 0 | 0 |
Does gensim.model.TfidfModel have the term frequency saved?
From the docs, they use the formula:
weights_i_j = frequency_i_j * log_2(D / doc_freq_i)
And when I prob the attributes of the dir(model) (TfidfModel object) with the following code:
>>> import gensim.downloader as api
>>> from gensim.models import TfidfModel
>>> from gensim.corpora import Dictionary
>>>
>>> dataset = api.load("text8")
>>> dct = Dictionary(dataset) # fit dictionary
>>> corpus = [dct.doc2bow(line) for line in dataset] # convert dataset to BoW format
>>>
>>> model = TfidfModel(corpus) # fit model
>>> dir(model)
I'm getting:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_adapt_by_suffix',
'_apply',
'_load_specials',
'_save_specials',
'_smart_save',
'dfs',
'id2word',
'idfs',
'initialize',
'load',
'normalize',
'num_docs',
'num_nnz',
'save',
'wglobal',
'wlocal']
But I can't seem to find where are the term frequencies stored.
If the term frequencies are not saved, is there a reason why? Since it's already stored to compute the weights anyways.
Is there a way to retrieve the term frequencies somehow during the fitting process?
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a large dataset containing a mix of words and short phrases, such as:
dataset = [
"car",
"red-car",
"lorry",
"broken lorry",
"truck owner",
"train",
...
]
I am trying to find a way to determine the most similar word from a short sentence, such as:
input = "I love my car that is red" # should map to "red-car"
input = "I purchased a new lorry" # should map to "lorry"
input = "I hate my redcar" # should map to "red-car"
input = "I will use my truck" # should map to "truck owner"
input = "Look at that yellow lorri" # should map to "lorry"
I have tried a number of approaches to this with no avail, including:
Vectoring the dataset and the input using TfidfVectorizer, then calculating the Cosine similarity of the vectorized input value against each individual, vectorized item value from the dataset.
The problem is, this only really works if the input contains the exact word(s) that are in the dataset - so for example, in the case where the input = "trai" then it would have a cosine value of 0, whereas I am trying to get it to map to the value "train" in the dataset.
The most obvious solution would be to perform a simple spell check, but that may not be a valid option, because I still want to choose the most similar result, even when the words are slightly different, i.e.:
input = "broke" # should map to "broken lorry" given the above dataset
If someone could suggest other potential approach I could try, that would be much appreciated.
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm trying to create a dataset to do sentiment analysis on news articles. I'm using Newspaper3k to scrape articles from the website. I scraped a few websites but didn't store the articles properly and hence I can't use them. When I try scraping the same websites again it only scrapes the new articles and not the ones it already scraped. Is there a way for me to scrape the articles I already scraped again??
| 1 | 1 | 0 | 0 | 0 | 0 |
Good day, everyone. So I found a paper that implement named entity recognition as pattern in AIML. As far as I know, in AIML must be uppercase and have no punctuation in it. But in the paper that I mention earlier, they use their pattern with entity and their value e.g Question:DIMANA,Others:LOKASI, etc. So I just want to ask guys, is it possible to write inside like that? Here is example code that had been provided in the paper.
<aiml version="2.0" encoding="UTF-8"?>
<category>
<pattern>
Question:DIMANA,Others:LOKASI,Organization:ITHB
</pattern>
<template>
Lokasi Universitas berada di Jalan....
</template>
</category>
</aiml>
By the way, I use Python AIML for the intepreter of AIML. Here is the link to the paper: https://journal.ithb.ac.id/telematika/article/view/130 (the paper is in Bahasa)
| 1 | 1 | 0 | 0 | 0 | 0 |
There are a few questions on SO dealing with using groupby with sparse matrices. However the output seem to be lists, dictionaries, dataframes and other objects.
I'm working on an NLP problem and would like to keep all the data in sparse scipy matrices during processing to prevent memory errors.
Here's the context:
I have vectorized some documents (sample data here):
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
df = pd.read_csv('groupbysparsematrix.csv')
docs = df['Text'].tolist()
vectorizer = CountVectorizer()
train_X = vectorizer.fit_transform(docs)
print("Dimensions of training set: {0}".format(train_X.shape))
print type(train_X)
Dimensions of training set: (8, 180)
<class 'scipy.sparse.csr.csr_matrix'>
From the original dataframe I use the date, in a day of the year format, to create the groups I would like to sum over:
from scipy import sparse, hstack
df['Date'] = pd.to_datetime(df['Date'])
groups = df['Date'].apply(lambda x: x.strftime('%j'))
groups_X = sparse.csr_matrix(groups.astype(float)).T
train_X_all = sparse.hstack((train_X, groups_X))
print("Dimensions of concatenated set: {0}".format(train_X_all.shape))
Dimensions of concatenated set: (8, 181)
Now I'd like to apply groupby (or a similar function) to find the sum of each token per day. I would like the output to be another sparse scipy matrix.
The output matrix would be 3 x 181 and look something like this:
1, 1, 1, ..., 2, 1, 3
2, 1, 3, ..., 1, 1, 4
0, 0, 0, ..., 1, 2, 5
Where the columns 1 to 180 represent the tokens and column 181 represents the day of the year.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have been going through many Libraries like whoosh/nltk and concepts like word net.
However I am unable to tackle my problem. I am not sure if I can find a library for this or I have to build this using the above mentioned resources.
Question:
My scenario is that I have to search for key words.
Say I have key words like 'Sales Document' / 'Purchase Documents' and have to search for them in a small 10-15 pages book.
The catch is:
Now they can also be written as 'Sales should be documented' or 'company selling should be written in the text files'. (For Sales Document - Keyword) Is there an approach here or will I have to build something?
The code for the POS Tags is as follows. If no library is available I will have to proceed with this.
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
from pandas import Series
import nltk
from nltk.corpus import wordnet
def tag(x):
return pos_tag(word_tokenize(x))
synonyms = []
antonyms = []
for syn in wordnet.synsets("Sales document"):
#print("Down2")
print (syn)
#print("Down")
for l in syn.lemmas():
print("
")
print(l)
synonyms.append(l.name())
if l.antonyms():
antonyms.append(l.antonyms()[0].name())
print(set(synonyms))
print(set(antonyms))
for i in synonyms:
print(tag(i))
Update:
We went ahead and made a python program - Feel free to fork it. (Pun intended)
Further the Git Dhund is very untidy right now will clean it once completed.
Currently it is still in a development phase.
The is the link.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a (large) list of parsed sentences (which were parsed using the Stanford parser), for example, the sentence "Now you can be entertained" has the following tree:
(ROOT
(S
(ADVP (RB Now))
(, ,)
(NP (PRP you))
(VP (MD can)
(VP (VB be)
(VP (VBN entertained))))
(. .)))
I am using the set of sentence trees to induce a grammar using nltk:
import nltk
# ... for each sentence tree t, add its production to allProductions
allProductions += t.productions()
# Induce the grammar
S = nltk.Nonterminal('S')
grammar = nltk.induce_pcfg(S, allProductions)
Now I would like to use grammar to generate new, random sentences. My hope is that since the grammar was learned from a specific set of input examples, then the generated sentences will be semantically similar. Can I do this in nltk?
If I can't use nltk to do this, do any other tools exist that can take the (possibly reformatted) grammar and generate sentences?
| 1 | 1 | 0 | 0 | 0 | 0 |
So when I was checking the implementation of a skip gram model in tensorflow using a movie dataset. I came across this function:
def generate_batch_data(sentences, batch_size, window_size, method='skip_gram'):
# Fill up data batch
batch_data = []
label_data = []
while len(batch_data) < batch_size:
# select random sentence to start
rand_sentence = np.random.choice(sentences)
# Generate consecutive windows to look at
window_sequences = [rand_sentence[max((ix-window_size),0):(ix+window_size+1)] for ix, x in enumerate(rand_sentence)]
# Denote which element of each window is the center word of interest
label_indices = [ix if ix<window_size else window_size for ix,x in enumerate(window_sequences)]
# Pull out center word of interest for each window and create a tuple for each window
if method=='skip_gram':
batch_and_labels = [(x[y], x[:y] + x[(y+1):]) for x,y in zip(window_sequences, label_indices)]
# Make it in to a big list of tuples (target word, surrounding word)
tuple_data = [(x, y_) for x,y in batch_and_labels for y_ in y]
elif method=='cbow':
batch_and_labels = [(x[:y] + x[(y+1):], x[y]) for x,y in zip(window_sequences, label_indices)]
# Make it in to a big list of tuples (target word, surrounding word)
tuple_data = [(x_, y) for x,y in batch_and_labels for x_ in x]
else:
raise ValueError('Method {} not implemented yet.'.format(method))
# extract batch and labels
batch, labels = [list(x) for x in zip(*tuple_data)]
batch_data.extend(batch[:batch_size])
label_data.extend(labels[:batch_size])
# Trim batch and label at the end
batch_data = batch_data[:batch_size]
label_data = label_data[:batch_size]
# Convert to numpy array
batch_data = np.array(batch_data)
label_data = np.transpose(np.array([label_data]))
return(batch_data, label_data)
But I have been trying to understand the code for days but haven't figured it out. The whole code is here if you want to have a broader perspective.
So, in the code, we have a number for the most frequent 10000 words. And we pass sentences in numeric form to the function above. Since this is a skip-gram model, we have to look at adjacent words. But how is that done in this algorithm? Wouldn't window_sequences = [rand_sentence[max((ix-window_size),0):(ix+window_size+1)] for ix, x in enumerate(rand_sentence)] create a window of words that are adjacent in frequency but not in sentence usage?
I would love a clarification here.
Thanks a lot!
| 1 | 1 | 0 | 1 | 0 | 0 |
I have a corpus of customer reviews and want to identify rare words, which for me are words that appear in less than 1% of the corpus documents.
I already have a working solution, but it is far too slow for my script:
# Review data is a nested list of reviews, each represented as a bag of words
doc_clean = [['This', 'is', 'review', '1'], ['This', 'is', 'review', '2'], ..]
# Save all words of the corpus in a set
all_words = set([w for doc in doc_clean for w in doc])
# Initialize a list for the collection of rare words
rare_words = []
# Loop through all_words to identify rare words
for word in all_words:
# Count in how many reviews the word appears
counts = sum([word in set(review) for review in doc_clean])
# Add word to rare_words if it appears in less than 1% of the reviews
if counts / len(doc_clean) <= 0.01:
rare_words.append(word)
Does anyone know a faster implementation for this? It seems to be very time-consuming to iterate for each individual words through each individual review.
Thanks in advance and best wishes,
Marcus
| 1 | 1 | 0 | 0 | 0 | 0 |
code like this:
train_corpus = "sentence_all.txt"
sentences = LineSentence(train_corpus)
model = Word2Vec(sentences, size=vector_size, window=window_size, min_count=min_count, workers=worker_count, iter=train_epoch)
print(model['一九九八年新年'])
the corpus file has been processd as list of token by LineSentence in gensim like this:
['本报', '讯', '河北邢台中桥商场', '以', '诚', '待客', ',', '以', '真品', '赢', '来', '回头客', '。', '1997年', ',', '商场', '利税', '比', '上年', '翻', '了', '一番', '多', ',', '员工', '人均', '年', '销售额', '达', '22.1万', '元', '。']
['中桥商场', '虽', '地处', '邢台市', ',', '但', '为了', '扩大', '销售', '半径', ',', '他们', '投资', '近', '万', '元', ',', '向', '邢台市', '19', '个', '县', '、', '市', '、', '区', '部分', '顾客', '赠阅', '《', '公关', '世界', '》', '及', '《', '中国', '质量', '万', '里', '行', '》', '杂志', ',', '扩大', '了', '商店', '的', '影响', '。']
then get the error:
KeyError: "word '一九九八年新年' not in vocabulary"
but only a few tokens are not in vocabulary, the others can get their word vector, then I don't know the reason.
| 1 | 1 | 0 | 0 | 0 | 0 |
What is the effect of assigning the same label to a bunch of sentences in doc2vec? I have a collection of documents that I want to learn vectors using gensim for a "file" classification task where file refers to a collection of documents for a given ID. I have several ways of labeling in mind and I want to know what would be the difference between them and which is the best -
Take a document d1, assign label doc1 to the tags and train. Repeat for others
Take a document d1, assign label doc1 to the tags. Then tokenize document into sentences and assign label doc1 to its tags and then train with both full document and individual sentences. Repeat for others
For example (ignore that the sentence isn't tokenized) -
Document - "It is small. It is rare"
TaggedDocument(words=["It is small. It is rare"], tags=['doc1'])
TaggedDocument(words=["It is small."], tags=['doc1'])
TaggedDocument(words=["It is rare."], tags=['doc1'])
Similar to above, but also assign a unique label for each sentence along with doc1. The full document has the all the sentence tags along with doc1.
Example -
Document - "It is small. It is rare"
TaggedDocument(words=["It is small. It is rare"], tags=['doc1', 'doc1_sentence1', 'doc1_sentence2'])
TaggedDocument(words=["It is small."], tags=['doc1', 'doc1_sentence1'])
TaggedDocument(words=["It is rare."], tags=['doc1', 'doc1_sentence2'])
I also have some additional categorical tags that I'd be assigning. So what would be the best approach?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am working on a NLP project about keyword extraction and I am a newbie in this field. My current task is about getting phrases (sub-strings) that are split from a sentence that I process before. I implemented from a source written in Python.
tmp = re.sub(stopword_pattern, '|', s.strip())
phrases = tmp.split("|")
for phrase in phrases:
phrase = phrase.strip().lower()
phrase_list.append(phrase)
As I read and understood, this procedure uses Regex to remove words from stopword_pattern and then replace them with '|' character from a sentence. Then, it split itself into array of strings by removing '|'. Here is an example:
From a sentence named s: and nonstrict inequations are considered
tmp: and|nonstrict|inequations|are|considered
phrases: ['and', 'nonstrict', 'inequations', 'are', 'considered']
I translated this to Java and here what I did:
sentence = sentence.trim();
if (sentence.equals("")) {
continue;
}
StringBuffer sb = new StringBuffer();
Matcher matcher = stopWordsPattern.matcher(sentence);
while (matcher.find()) {
matcher.appendReplacement(sb, "|");
}
String tempResult = sb.toString();
String[] phrases = tempResult.split("|");
for (String phrase : phrases) {
phrase = phrase.trim().toLowerCase();
phraseList.add(phrase);
}
But with that code, the result is difference:
tmp: |and||nonstrict||inequations||are||considered|
phrases:[|, a, n, d, |, |, n, o, n, s, t, r, i, c, t, |, |, i, n, e, q, u, a, t, i, o, n, s, |, |, a, r, e, |, |, c, o, n, s, i, d, e, r, e, d, |]
I checked a stop_pattern from 2 codes and both are correct. My question is how to setup string pattern "|" in java, or more specifically, is how to make Pattern and Matcher in Java work like the above source from Python?
Many thanks about that!
P/s: I tried with other split string like '~' or '_'..., but they can be noised by natural sentence from human language, so I use '|'.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a dataset with two columns: customer id and addresses:
id addresses
1111 asturias 32, benito juarez, CDMX
1111 JOSE MARIA VELASCO, CDMX
1111 asturias 32 DEPT 401, INSURGENTES, CDMX
1111 deportes
1111 asturias 32, benito juarez, MIXCOAC, CDMX
1111 cd. de los deportes
1111 deportes, wisconsin
2222 TORRE REFORMA LATINO, CDMX
2222 PERISUR 2890
2222 WE WORK, CDMX
2222 WEWORK, TORRE REFORMA LATINO, CDMX
2222 PERISUR: 2690, COYOCAN
2222 TORRE REFORMA LATINO
I am interested to find number of different addresses for each customers. For example, for the customer id 1111, there are 3 different addresses:
[asturias 32, benito juarez, CDMX,
asturias 32 DEPT 401, INSURGENTES, CDMX,
asturias 32, benito juarez, MIXCOAC, CDMX]
[JOSE MARIA VELASCO, CDMX]
[deportes,
cd. de los deportes,
deportes, wisconsin]
I wrote a code in python which can only show similarity between two consecutive rows: row i and row i+1 (score of 0 means completely dissimilar and 1 means completely similar).
id addresses score
1111 asturias 32, benito juarez, CDMX 0
1111 JOSE MARIA VELASCO, CDMX 0
1111 asturias 32 DEPT 401, INSURGENTES, CDMX 0
1111 deportes 0
1111 asturias 32, benito juarez, MIXCOAC, CDMX 0
1111 cd. de los deportes 0.21
1111 deportes, wisconsin 0
2222 TORRE REFORMA LATINO, CDMX 0
2222 PERISUR 2890 0
2222 WE WORK, CDMX 0.69
2222 WEWORK, TORRE REFORMA LATINO, CDMX 0
2222 PERISUR: 2690, COYOCAN 0
2222 TORRE REFORMA LATINO
If score > 0.20, I am considering them two different addresses. Following is my code:
import nltk
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
import unicodedata
import unidecode
import string
from sklearn.feature_extraction.text import TfidfVectorizer
data=pd.read_csv('address.csv')
nltk.download('punkt')
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(
nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
def cosine_sim(text1, text2):
tfidf = vectorizer.fit_transform([text1, text2])
return ((tfidf * tfidf.T).A)[0, 1]
cnt = np.array(np.arange(0, 5183))
indx = []
for i in cnt:
print cosine_sim(data['address'][i], data['address'][i + 1])
But above code is not able to compare each possible rows for a particular customer id. I want output like below:
id unique address
1111 3
2222 3
3333 2
| 1 | 1 | 0 | 0 | 0 | 0 |
After 85 epochs the loss (a cosine distance) of my model (a RNN with 3 LSTM layers) become NaN. Why does it happen and how can I fix it? Outputs of my model also become NaN.
My model :
tf.reset_default_graph()
seqlen = tf.placeholder(tf.int32, [None])
x_id = tf.placeholder(tf.int32, [None, None])
y_id = tf.placeholder(tf.int32, [None, None])
embeddings_matrix = tf.placeholder(np.float32, [vocabulary_size, embedding_size])
x_emb = tf.nn.embedding_lookup(embeddings_matrix, x_id)
y_emb = tf.nn.embedding_lookup(embeddings_matrix, y_id)
cells = [tf.contrib.rnn.LSTMCell(s, activation=a) for s, a in [(400, tf.nn.relu), (400, tf.nn.relu), (400, tf.nn.tanh)]]
cell = tf.contrib.rnn.MultiRNNCell(cells)
outputs, _ = tf.nn.dynamic_rnn(cell, x_emb, dtype=tf.float32, sequence_length=seqlen)
loss = tf.losses.cosine_distance(tf.nn.l2_normalize(outputs, 2), tf.nn.l2_normalize(y_emb, 2), 1)
tf.summary.scalar('loss', loss)
opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
merged = tf.summary.merge_all()
The output of the training :
Epoch 80/100
Time : 499 s Loss : 0.972911523852701 Val Loss : 0.9729658
Epoch 81/100
Time : 499 s Loss : 0.9723407568655597 Val Loss : 0.9718646
Epoch 82/100
Time : 499 s Loss : 0.9718870568505438 Val Loss : 0.971976
Epoch 83/100
Time : 499 s Loss : 0.9913996352643445 Val Loss : 0.990693
Epoch 84/100
Time : 499 s Loss : 0.9901496524596137 Val Loss : 0.98957264
Epoch 85/100
Time : 499 s Loss : nan Val Loss : nan
Epoch 86/100
Time : 498 s Loss : nan Val Loss : nan
Epoch 87/100
Time : 498 s Loss : nan Val Loss : nan
Epoch 88/100
Time : 499 s Loss : nan Val Loss : nan
Epoch 89/100
Time : 498 s Loss : nan Val Loss : nan
Epoch 90/100
Time : 498 s Loss : nan Val Loss : nan
And here sis the curve of the loos during the entire training :
The blue curve is the loss on training data and the orange one in the loss on validation data.
The learning rate used for ADAM is 0.001.
My x and y got the following shape : [batch size, maximum sequence length], they're both set to None, because the last batch of each epoch is smaller, and the maximal sequence length change at each batch.
x and y go through an embedding lookup and become of shape [batch size, maximum sequence length, embedding size], the embedding for the padding word is a vector of 0.
The dynamic rnn take the length of each sequence (seqlen in the code, with a shape of [batch size]) so it will only make predictions for the exact length of each sequence and the rest of the output will be padded with vectors of zero, as for y.
My guess is the values of the output become so close of zero, that once they're squared to compute the cosine distance they become 0 so it leads to a division by zero.
Cosine distance formula :
I don't know if I'm right, neither how to prevent this.
EDIT:
I just checked weights of every layers and they're all NaN
SOLVED:
Using a l2 regularization worked.
tf.reset_default_graph()
seqlen = tf.placeholder(tf.int32, [None])
x_id = tf.placeholder(tf.int32, [None, None])
y_id = tf.placeholder(tf.int32, [None, None])
embeddings_matrix = tf.placeholder(np.float32, [vocabulary_size, embedding_size])
x_emb = tf.nn.embedding_lookup(embeddings_matrix, x_id)
y_emb = tf.nn.embedding_lookup(embeddings_matrix, y_id)
cells = [tf.contrib.rnn.LSTMCell(s, activation=a) for s, a in [(400, tf.nn.relu), (400, tf.nn.relu), (400, tf.nn.tanh)]]
cell = tf.contrib.rnn.MultiRNNCell(cells)
outputs, _ = tf.nn.dynamic_rnn(cell, x_emb, dtype=tf.float32, sequence_length=seqlen)
regularizer = tf.reduce_sum([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
cos_distance = tf.losses.cosine_distance(tf.nn.l2_normalize(outputs, 2), tf.nn.l2_normalize(y_emb, 2), 1)
loss = cos_distance + beta * regularizer
opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
tf.summary.scalar('loss', loss)
tf.summary.scalar('regularizer', regularizer)
tf.summary.scalar('cos_distance', cos_distance)
merged = tf.summary.merge_all()
| 1 | 1 | 0 | 0 | 0 | 0 |
I am working on tokenizing, lemmatizing and removing stopwords from a document. However, Spacy is throwing an error saying that the token.pos_ module does not accept 'str'. I believe strings are the proper format, correct me if I am wrong. How do I fix this error?
words = []
classes = []
documents = []
ignore_words = ['?']
# loop through each sentence in our training data
for pattern in training_data:
# tokenize each word in the sentence
w = gensim.utils.simple_preprocess(str(pattern['sentence']), deacc=True)
# add to our words list
words.extend(w)
# add to documents in our corpus
documents.append((w, pattern['class']))
# add to our classes list
if pattern['class'] not in classes:
classes.append(pattern['class'])
nltk.download('stopwords')
stop_words = stopwords.words('english')
stop_words.extend(["be", "use", "fig"])
words = [word for word in words if word not in stop_words]
# stem and lower each word and remove duplicates
import en_core_web_lg
nlp = en_core_web_lg.load()
print(words[0:10])
words = [token.lemma_ for token in words if token.pos_ in postags]
words = list(set(words))
AttributeError Traceback (most recent call last)
<ipython-input-72-5c31e2b5a13c> in <module>()
26
27 from spacy import tokens
---> 28 words = [token.lemma_ for token in words if token.pos in postags]
29 words = list(set(words))
30
<ipython-input-72-5c31e2b5a13c> in <listcomp>(.0)
26
27 from spacy import tokens
---> 28 words = [token.lemma_ for token in words if token.pos in postags]
29 words = list(set(words))
30
AttributeError: 'str' object has no attribute 'pos'
| 1 | 1 | 0 | 0 | 0 | 0 |
def cbow(phrase1,phrase2):
vec1=cbow(phrase1)
vec2=cbow(phrase2)
print(vec)
return np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))
cbow("green apple","green apple")
TypeError: cbow() missing 1 required positional argument: 'phrase2'
| 1 | 1 | 0 | 0 | 0 | 0 |
I was trYing to save session in model so that i can use it later on but i am getting an error everytime. My code is like:
with tf.Session() as sess:
sess.run(init)
for j in range(3):
for i in range(xtest.shape[0]):
_, indices = sess.run(pred, feed_dict={x_train: xtrain, x_test: xtest[i,:]})
pred_label = getMajorityPredictions(ytrain, indices)
actual_val = get_char( int( (ytest[i]).argmax() ) )
# print("test: ", i, "prediction: ", get_char(pred_label), " actual: ", actual_val)
# print(pred_label, actual_val, type(pred_label), type(actual_val), sep=" --> ")
if get_char(pred_label) == actual_val:
accuracy += 1/len(xtest)
# print((i / (xtest.shape[0])) * 100)
# os.system("cls")
print("accuracy: ",accuracy)
savedPath = saver.save(sess, "/tmp/model.ckpt")
print("Model saved at: " ,savedPath)
and the error is like:
Traceback (most recent call last):
File "prac3.py", line 74, in <module>
saver = tf.train.Saver()
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1239, in __init__
self.build()
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1248, in build
self._build(self._filename, build_save=True, build_restore=True)
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1272, in _build
raise ValueError("No variables to save")
ValueError: No variables to save
| 1 | 1 | 0 | 1 | 0 | 0 |
When attempting to find the entities in a long input of text, Google Cloud's natural language program is grouping together words and then getting their incorrect entity. Here is my program:
def entity_recognizer(nouns):
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/superaitor/Downloads/link"
text = ""
for words in nouns:
text += words + " "
client = language.LanguageServiceClient()
if isinstance(text, six.binary_type):
text = text.decode('utf-8')
document = types.Document(
content=text.encode('utf-8'),
type=enums.Document.Type.PLAIN_TEXT)
encoding = enums.EncodingType.UTF32
if sys.maxunicode == 65535:
encoding = enums.EncodingType.UTF16
entity = client.analyze_entities(document, encoding).entities
entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')
for entity in entity:
#if entity_type[entity.type] is "PERSON":
print(entity_type[entity.type])
print(entity.name)
Here nouns is a list of words. I then turn that into a string(i've tried multiple ways of doing so, all give the same result), but yet the program spits out output like:
PERSON
liberty secularism etching domain professor lecturer tutor royalty
government adviser commissioner
OTHER
business view society economy
OTHER
business
OTHER
verge industrialization market system custom shift rationality
OTHER
family kingdom life drunkenness college student appearance income family
brink poverty life writer variety attitude capitalism age process
production factory system
Any input on how to fix this?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am looking for ways to extract specific paragraphs out of strings. I have a lot of documents which I want to use for topic modeling, but these contain tables, figures, headers, etc. I only want to use the summary which usually is in a document. But the summaries aren't clearly declared.
I converted the PDFs to text and tried something like this but it did not work out well, because the summaries are always declared in a different way:
def get_summary(text):
subject = ""
copy = False
textlines = text.splitlines()
for line in textlines:
#print line
if line.strip() == 'SUMMARY_BEGIN':
copy = True
elif line.strip() == 'SUMMARY_END':
copy = False
elif copy:
#print(line)
subject += line
return subject
I dont want search for a summary between 100 different possible substrings.
Edit: look alike example:
Date
21 Jun 2017
name name [abc]
name name [abc]
name name [cbd]
name name
name name
name name
name name
name name
nonsense-word1
nonsense-word1
nonsense-word1
12354
37264324
Summary:
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document.
32 463264
324324
324432
32424
nonsense-word2
nonsense-word2
nonsense-word2
nonsense-word2
nonsense-word2
nonsense-word2
324
24442
name name
name name
name name
name name
3244324324
Date
21 Jun 2017
Date
21 Jun 2017
Date
21 Jun 2017
electronically validated
electronically validated
electronically validated
electronically validated
electronically validated
763254 3276 4276457234
| 1 | 1 | 0 | 0 | 0 | 0 |
temp = []
for i in chunks:
vectorizer2 = CountVectorizer()
vectorizer2.fit_transform(i).todense()
temp.append(vectorizer2)
print(vectorizer2.vocabulary_)
x = [LinearSVC_classifier.classify(y) for y in temp ]
I have a document that I am trying to put in the proper format to use my classifiers against. I have broken down the doc into individual lists. So the data looks like this..
chunks = [[ 'sentence1'] , ['sentence2'], ['sentences']]
The function I have written gets me partially there but then I get this error.
ValueError: empty vocabulary; perhaps the documents only contain stop words
but also getting this...
{u'and': 4, u'www': 53, u'is': 25, u'some': 44, u'commitment': 10}
If I run each sentences manually and individually they each work with 0 errors and the classifier works. I am hoping my results at the end would look like this.
['sentence1', 'no'] , ['senence2', 'yes']
or anyway i can see each sentences classification works honestly. I am just unsure where the error lies and if it is fixable or I need a new approach. Any help would be greatly appreciated.
ValueError Traceback (most recent call last)
<ipython-input-608-c2fb95ef6621> in <module>()
4 for i in chunks:
5 print (i)
----> 6 vectorizer2.fit_transform(i).todense()
7 temp.append(vectorizer2)
8 print(vectorizer2.vocabulary_)
C:\Program Files\Anaconda2\lib\site-
packages\sklearn\feature_extraction\text.pyc in fit_transform(self,
raw_documents, y)
867
868 vocabulary, X = self._count_vocab(raw_documents,
--> 869 self.fixed_vocabulary_)
870
871 if self.binary:
C:\Program Files\Anaconda2\lib\site-
packages\sklearn\feature_extraction\text.pyc in _count_vocab(self,
raw_documents, fixed_vocab)
809 vocabulary = dict(vocabulary)
810 if not vocabulary:
--> 811 raise ValueError("empty vocabulary; perhaps the
documents only"
812 " contain stop words")
813
ValueError: empty vocabulary; perhaps the documents only contain stop words
| 1 | 1 | 0 | 0 | 0 | 0 |
So Im trying to find out if a company has been acquired by another company or not. Lets say I search for halli labs and want to know whether its been acquired or not. If yes then I need to know the parent company name. My approach is to google search "Halli labs parent company". Then Ive scraped all the text on the first page, all the corresponding links, date etc. Then I can run pos tag, generate bigrams, trigrams etc and feed it to some algorithm to find if the text is about acquisition, if yes then pull out the company name.
The problem now is that, the name of the companies are getting tagged as "PERSON", is there a way I can resolve this ?
Also is my approach good enough ? Because thats basically how a human would find whether a company has been acquired or not ?
nltk.ne_chunk(nltk.pos_tag(nltk.tokenize.word_tokenize("Google has acquired Halli Labs, a four-month old start-up out of Bengaluru that is developing artificial intelligence and machine learning")))
| 1 | 1 | 0 | 1 | 0 | 0 |
I have an audio file which is converted into text by google speech API. I want a new feature like while clicking on the text at the same time audio timing should move to match a place in an audio file?
Please refer this(http://www.ted.com/talks/reed_hastings_how_netflix_changed_entertainment_and_where_it_s_headed/transcript#t-128497)
| 1 | 1 | 0 | 1 | 0 | 0 |
I have implemented a fuzzy matching algorithm and I would like to evaluate its recall using some sample queries with test data.
Let's say I have a document containing the text:
{"text": "The quick brown fox jumps over the lazy dog"}
I want to see if I can retrieve it by testing queries such as "sox" or "hazy drog" instead of "fox" and "lazy dog".
In other words, I want to add noise to strings to generate misspelled words (typos).
What would be a way of automatically generating words with typos for evaluating fuzzy search?
| 1 | 1 | 0 | 0 | 0 | 0 |
So, basically I have a test corpus of 350 text files (350 rows) and I made a ml model to predict the gender of an author based on the SMS in each text file.
After preprocessing is done these are my final lines of code :
(Joined is preprocessed column in dataframe df)
from sklearn.model_selection import train_test_split
from sklearn import cross_validation
from sklearn.feature_extraction.text import CountVectorizer
y = df['Gender']
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
df['Joined'], y,
test_size=0.20,random_state=53)
count_vectorizer = CountVectorizer(stop_words='english')
count_train = count_vectorizer.fit_transform(X_train.values)
count_test = count_vectorizer.transform(X_test.values)
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
nb_classifier = MultinomialNB()
nb_classifier.fit(count_train, y_train)
pred = nb_classifier.predict(count_test)
metrics.accuracy_score(y_test, pred)
Now I have a new test corpus which has 150 text files(150 rows) and I have to predict the gender of these files based on my previous model!
I have made a new dataframe called newdf and preprocessed the test corpus files into a column called new_test which has 150 rows.
Now how can I use my previous nb_classifier model on this new_test column?
| 1 | 1 | 0 | 1 | 0 | 0 |
With spaCy (2.0.11 according to spacy.info()), I'm trying to identify token patterns using the Matcher, but am not getting the expected results. The token offsets in the match objects do not correspond to the offsets of the tokens that should be matched in the text.
Here is a simplified code snippet to show what I'm doing:
import spacy
from spacy.matcher import Matcher
nlp = spacy.load('en')
text = "This has not gone far. The end."
doc = nlp(text)
pattern1 = [{'POS': 'VERB'}, {'LEMMA': 'not'}, {'POS': 'VERB'}] # match has not gone
pattern2 = [{'POS': 'DET'}, {'POS': 'NOUN'}] # match The end
matcher = Matcher(nlp.vocab)
matcher.add('rule1', None, pattern1)
matcher.add('rule2', None, pattern2)
matches = matcher(doc)
for match in matches:
print(doc[match[1]], doc[match[2]], match)
The output I get is:
has far (15137773209560627690, 1, 4)
The . (16952143625379849586, 6, 8)
The output I'm expecting is:
has gone (15137773209560627690, 1, 3)
The end (16952143625379849586, 6, 7)
So the end token offset of the match is that of the token after the last token matched by the pattern. Is this the expected behaviour?
More generally, I'm trying to produce the TokensRegex-style behaviour of being able to add custom annotations to individual tokens within a given match (e.g. adding a negated=TRUE annotation to "has" and "gone" and a negation=TRUE annotation to the adverb "not" within the same match). Adding a single annotation to a match with a callback function is possible, but that's not quite what I'm after. Is this possible (yet)?
| 1 | 1 | 0 | 0 | 0 | 0 |
I would like to make a new entity: let's call it "medicine" and then train it using my corpora. From there, identify all the entities of "medicine". Somehow my code is not working, could anyone help me?
import nltk
test= input("Please enter your file name")
test1= input("Please enter your second file name")
with open(test, "r") as file:
new = file.read().splitlines()
with open(test1, "r") as file2:
new1= file2.read().splitlines()
for s in new:
for x in new1:
sample = s.replace('value', x)
sample1 = ''.join(str(v) for v in sample)
print(sample1)
sentences = nltk.sent_tokenize(sample1)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)
print(sentences)
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'label') and t.label:
if t.label() == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
| 1 | 1 | 0 | 0 | 0 | 0 |
So I'm currently working on 5 dictionaries and very possibly more in the futur, with at least 257000+ entries each. Consider them as 5 huge text files(size: 10-20 Mb) with, say, 10-30 characters each line would be fine.
An example of an entry be like:
abaissements volontaires,abaissement volontaire.N+NA:mp
My mission is to find out duplicate words between/among different dictionaires.
So first of all, I have to process the file to get, for example, only abaissements volontaires from the example. After this part, my idea is to have a list that contains elements like:
dict_word_list = [[dict_A, [word1, word2, ...]], [dict_B, [word1, word2, ...]]]
The choice of lists over dicts is simply because dicts are unordered in Python and I have to know the name of the corresponding dictionary of each word list, so I put the corresponding dictionary names in element 0 of each list.
My question is how to find out duplicates between/among these huge lists and at the same time keep dictionary names?
I tried if not in list but due to the file size and a very old processor(an intel core i3 in an old shabby laptop at work and I cannot use my own laptop due to confidentiality issues) , the program simply bugs there.
Maybe set would be a solution, but how do I shuffle the comparison? I would like to have results like:
Duplicates dict_A, dict_B: [word1, word2, word3, ...]
Duplicates dict_B, dict_C: [word1, word2, word3, ...]
Duplicates dict_A, dict_B, dict_C: [word1, word2, word3, ...]
| 1 | 1 | 0 | 0 | 0 | 0 |
I have been working on finding the lower level clinical terms in given document either in the same exact words or in different words but the same meaning. I used cosine similarity matching for the given text with every terms I have to match with and I do get the value of how much it has matched the given text highest cos value gives me the exact value.
sent_list = process.SBD("The patient has been given paracetamol for fever in interval of every two hour. There has been sever headache and abnorm of the labor. Continuation of these medicine might lead to abdomen has been crushing.")
output:
[['Arenaviral haemorrhagic fever'], ['Abnormal labor'], ['Abdomen crushing']]
but I also need to get the index of the words which has matched in the text
Any algorithm to get the index of words matched in the given text.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a classification problem which requires some optimization, as my results are not quite adequate.
I'm using the DNNClassifier for a huge dataset in order to classify items in 5 different classes (labels). I have over 2000 distinct items (in a hashbucket column with size 2000 and dims 6 - is this adequate?) and multiple numeric columns for said classification.
My problem is the following: the amount of items belonging in each class is very variable. Class 1 is very common, class 2 is common but classes 3 4 and 5 are highly uncommon (under 2% of the dataset) but they are the most interesting ones in my test case. Even if I tweak the network size/number of neurons or the training epoch, I get close to no results in classes 3, 4 and 5, so class 1 and 2 are clearly overfitted.
I saw the weight_column option in the documentation - would that be a good idea to change the learning weight of these three class to "normalize" the weight in each class ? Is there a more efficient way to get better results on rarer cases without losing the detection precision on the common classes?
Many thanks!
| 1 | 1 | 0 | 1 | 0 | 0 |
filename='metamorphosis_clean.txt'
file=open(filename,'rt')
text=file.read()
file.close()
from nltk import sent_tokenize
sentences=sent_tokenize(text)
print(sentences[0])
Error:
Traceback (most recent call last):
File "split_into_sentenes.py", line 1, in <module>
import nltk
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 114, in <module>
from nltk.collocations import *
File "/usr/local/lib/python2.7/dist-packages/nltk/collocations.py", line 37, in <module>
from nltk.probability import FreqDist
File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 47, in <module>
from collections import defaultdict, Counter
File "/usr/local/lib/python2.7/dist-packages/nltk/collections.py", line 13, in <module>
import pydoc
File "/usr/lib/python2.7/pydoc.py", line 56, in <module>
import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
File "/usr/lib/python2.7/inspect.py", line 39, in <module>
import tokenize
File "/usr/lib/python2.7/tokenize.py", line 39, in <module>
COMMENT = N_TOKENS
NameError: name 'N_TOKENS' is not defined
| 1 | 1 | 0 | 1 | 0 | 0 |
I use the gensim library to create a word2vec model. It contains the function predict_output_words() which I understand as follows:
For example, I have a model that is trained with the sentence: "Anarchism does not offer a fixed body of doctrine from a single particular world view instead fluxing and flowing as a philosophy."
and then I use
model.predict_output_words(context_words_list=['Anarchism', 'does', 'not', 'offer', 'a', 'fixed', 'body', 'of', 'from', 'a', 'single', 'particular', 'world', 'view', 'instead', 'fluxing'], topn=10).
In this situation, could I get/predict the correct word or the omitted word 'doctrine'?
Is this the right way? Please explain this function in detail.
| 1 | 1 | 0 | 0 | 0 | 0 |
My goal is to create a RNN-CNN network in Keras that predicts categorical outputs based on paragraphs of text. In my current model the paragraphs are first embedded into feature vectors the fed into 2 cuDNNGRU layers, 4 Conv1D and MaxPooling layers, then to a Dense output layer.
However, I found a reference to a multi channel approach to dealing with word vectors that involved copying the initial vectors, running one set through a CNN layer then summing the output with the copy before pooling. This was done to prevent backpropogation into one set of vectors and therefore retain some semantic ideas from the original word vectors.
I've tried searching for this but the only thing associated with multi-channels and CNN is using multiple sizes of n-gram kernels. Does Keras offer any sort of functionality that could be used to achieve this?
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm trying to build an n-gram markov model from a given piece of text, and then access the transition table for it so I can calculate the conditional entropy for each sequence of words of length n (the grams).
For example, in a 2-gram model, after reading in a corpus of text
"dogs chase cats dogs chase cats dogs chase cats
dogs chase cats dogs chase cats dogs chase cats
dogs chase cats dogs chase cats dogs chase cats
dogs chase people"
and building an internal transition table, the state "dogs chase" may transition to the state "chase cats" with probability 0.9, and to state "chase people" with probability 0.1. If I know of the possible transitions, I can calculate the conditional entropy.
Are there any good python libraries for doing this? I've checked NLTK, SRILM, and others but haven't found much.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have POS tagged some words with nltk.pos_tag(), so they are given treebank tags. I would like to lemmatize these words using the known POS tags, but I am not sure how. I was looking at Wordnet lemmatizer, but I am not sure how to convert the treebank POS tags to tags accepted by the lemmatizer. How can I perform this conversion simply, or is there a lemmatizer that uses treebank tags?
| 1 | 1 | 0 | 0 | 0 | 0 |
**edit: I’ve looked more into it and I’ll present it easier for both you guys and for me:
specific str, a bunch of stuff that I can’t know
the str inside the square brackets is what I need to find.
So how do I present the bunch of stuff inside?
I tried .* and .*? And both did not work..
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a problem that I have not been able to solve. I have 4 .txt files each between 30-70GB. Each file contains n-gram entries as follows:
blabla1/blabla2/blabla3
word1/word2/word3
...
What I'm trying to do is count how many times each item appear, and save this data to a new file, e.g:
blabla1/blabla2/blabla3 : 1
word1/word2/word3 : 3
...
My attempts so far has been simply to save all entries in a dictionary and count them, i.e.
entry_count_dict = defaultdict(int)
with open(file) as f:
for line in f:
entry_count_dict[line] += 1
However, using this method I run into memory errors (I have 8GB RAM available). The data follows a zipfian distribution, e.g. the majority of the items occur only once or twice.
The total number of entries is unclear, but a (very) rough estimate is that there is somewhere around 15,000,000 entries in total.
In addition to this, I've tried h5py where all the entries are saved as a h5py dataset containing the array [1], which is then updated, e.g:
import h5py
import numpy as np
entry_count_dict = h5py.File(filename)
with open(file) as f:
for line in f:
if line in entry_count_dict:
entry_count_file[line][0] += 1
else:
entry_count_file.create_dataset(line,
data=np.array([1]),
compression="lzf")
However, this method is way to slow. The writing speed gets slower and slower. As such, unless the writing speed can be increased this approach is implausible. Also, processing the data in chunks and opening/closing the h5py file for each chunk did not show any significant difference in processing speed.
I've been thinking about saving entries which start with certain letters in separate files, i.e. all the entries which start with a are saved in a.txt, and so on (this should be doable using defaultdic(int)).
However, to do this the file have to iterated once for every letter, which is implausible given the file sizes (max = 69GB).
Perhaps when iterating over the file, one could open a pickle and save the entry in a dict, and then close the pickle. But doing this for each item slows down the process quite a lot due to the time it takes to open, load and close the pickle file.
One way of solving this would be to sort all the entries during one pass, then iterate over the sorted file and count the entries alphabetically. However, even sorting the file is painstakingly slow using the linux command:
sort file.txt > sorted_file.txt
And, I don't really know how to solve this using python given that loading the whole file into memory for sorting would cause memory errors. I have some superficial knowledge of different sorting algorithms, however they all seem to require that the whole object to be sorted needs get loaded into memory.
Any tips on how to approach this would be much appreciated.
| 1 | 1 | 0 | 0 | 0 | 0 |
Let me explain, i'm working with an Artificial Neural Network.
This model has 15 variables, 14 independents and one dependent.
In the independent variables i've 3 categorical variables
(day of week, month, direction(north,south, etc...)).
I already enconde them (monday = 1, tuesday = 2, and so...),
also i hot encode them
(monday = [1,0,0,0], tuesday = [0,1,0,0]).
My question is, How can i make a prediction with new values, somethig like this.
X=['Monday','January','South']
Here is the code
# Classification template
# Importing the libraries
import numpy as np
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('clean.csv')
X = dataset.iloc[:, [4,5,6,9,12,15,16]].values
y = dataset.iloc[:, 14].values
#Encoding categorical Data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelenconder_X = LabelEncoder()
X[:,1] = labelenconder_X.fit_transform(X[:,1])
labelenconder_X_2 = LabelEncoder()
X[:,2] = labelenconder_X_2.fit_transform(X[:,2])
labelenconder_X_7 = LabelEncoder()
X[:,4] = labelenconder_X_7.fit_transform(X[:,4])
labelenconder_X_9 = LabelEncoder()
X[:,5] = labelenconder_X_9.fit_transform(X[:,5])
labelenconder_X_10 = LabelEncoder()
X[:,6] = labelenconder_X_10.fit_transform(X[:,6])
onehotencoder = OneHotEncoder(categorical_features=[1,2,4,5,6])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# Feature Scaling
#from sklearn.preprocessing import StandardScaler
#sc = StandardScaler()
#X_train = sc.fit_transform(X_train)
#X_test = sc.transform(X_test)
# Fitting classifier to the Training set
# Create your classifier here
import keras
from keras.models import Sequential
from keras.layers import Dense
classifier = Sequential()
#INPUT LAYER AND HIDDEN LAYER
classifier.add(Dense(units = 5, kernel_initializer = 'uniform', activation = 'relu', input_dim =9))
#ADDING SECOND HIDDEN LAYER
classifier.add(Dense(units = 5, kernel_initializer = 'uniform', activation = 'relu'))
#adding output node
classifier.add(Dense(units= 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
#Applygin Stochasting Gradient Descent
classifier.compile(optimizer='adam', loss = 'binary_crossentropy', metrics=['accuracy'])
classifier.fit(X_train, y_train, batch_size =28, epochs = 100)
classifier.save('ANN2.h5')
model = keras.models.load_model('ANN2.h5')
y_predict = model.predict(X_test)
y_predict = (y_predict > 0.40)
| 1 | 1 | 0 | 1 | 0 | 0 |
Is there any python module (may be in nltk python) to remove internet slang/ chat slang like "lol","brb" etc. If not can some one provide me a CSV file comprising of such vast list of slang?
The website http://www.netlingo.com/acronyms.php gives the list of acronyms but I am not able to find any CSV files for using them in my program.
| 1 | 1 | 0 | 0 | 0 | 0 |
I am using CountVectorizer to ready a dataset for ML. I want to filter out the rare words and I use the parameter of CountVectorizer, minDF or minTF for that. I would also like to remove items that appear 'often' in my dataset. I do not see a maxTF or maxDF parameter I can set. Is there a good way to do this?
df = spark.createDataFrame(
[(0, ["a", "b", "c","b"]), (1, ["a", "b", "b", "c", "a"])],
["label", "raw"])
So in this case if I wanted to remove parameters that appeared '4' times or 40% of the time, and, those that appeared 2 times or less. This would remove 'b' and 'c'.
Currently I run CountVectorizer(minDf=3......) for the lower bound req. How can I filter out the items that appear more often than I want to model on.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have to convert a log file into a json file to train a unsupervised model.
The log file is in format -
40.77.167.191, 172.16.30.15 - - [08/May/2018:03:29:15 +0530] "GET /speedwav-full-chrome-side-beading-for-tata-indigo-cs-46901.html HTTP/1.1" 403 162 <0.000> <-> "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
66.249.79.25, 172.16.30.15 - - [08/May/2018:03:29:17 +0530] "GET /schneider-dc-control-relays-ca4kn31-t008000721.html HTTP/1.1" 200 14443 <0.445> <0.445> "-" "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
66.249.79.25, 172.16.30.15 - - [08/May/2018:03:29:19 +0530] "GET /ajax/pdp/recentlyviewed/1184932 HTTP/1.1" 200 2 <0.089> <0.089> "https://www.tolexo.com/orient-18w-eternal-surface-panel-square-led-light-18w01-t14ori0043.html" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
I want to get the file in format -
40.77.167.191, 172.16.30.15 - - [08/May/2018:03:29:15 +0530] "GET /speedwav-full-chrome-side-beading-for-tata-indigo-cs-46901.html HTTP/1.1" 403 162 <0.000> <-> "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
66.249.79.25, 172.16.30.15 - - [08/May/2018:03:29:17 +0530] "GET /schneider-dc-control-relays-ca4kn31-t008000721.html HTTP/1.1" 200 14443 <0.445> <0.445> "-" "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
66.249.79.25, 172.16.30.15 - - [08/May/2018:03:29:19 +0530] "GET /ajax/pdp/recentlyviewed/1184932 HTTP/1.1" 200 2 <0.089> <0.089> "https://www.tolexo.com/orient-18w-eternal-surface-panel-square-led-light-18w01-t14ori0043.html" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
and then create a json file for it.
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a document of user survey:
Score Comment
8 Rapid bureaucratic affairs. Reports for policy...
4 There needs to be communication or feed back f...
7 service is satisfactory
5 Good
5 There is no
10 My main reason for the product is competition ...
9 Because I have not received the results. And m...
5 no reason
I want to determine which keywords correspond to a higher score, and which keywords correspond to a lower score.
My idea is to construct a table of the words (or, a "word vector" dictionary), which will contain the scores it is associated with, and the number of times that score has been associated with that sentence.
Something like the following:
Word Score Count
Word1: 7 1
4 2
Word2: 5 1
9 1
3 2
2 1
Word3: 9 3
Word4: 8 1
9 1
4 2
... ... ...
Then, for each word, the average score is average of all the scores that word is associated with.
To do this, my code is the following:
word_vec = {}
# col 1 is the word, col 2 is the score, col 3 is the number of times it occurs
for i in range(len(data)):
sentence = data['SurveyResponse'][i].split(' ')
for word in sentence:
word_vec['word'] = word
if word in word_vec:
word_vec[word] = {'Score':data['SCORE'][i], 'NumberOfTimes':(word_vec[word]['NumberOfTimes'] += 1)}
else:
word_vec[word] = {'Score':data['SCORE'][i], 'NumberOfTimes':1}
But this code gives me the following error:
File "<ipython-input-144-14b3edc8cbd4>", line 9
word_vec[word] = {'Score':data['SCORE'][i], 'NumberOfTimes':(word_vec[word]['NumberOfTimes'] += 1)}
^
SyntaxError: invalid syntax
Could someone please show me the correct way to do this?
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a text file with 11965 entries that looks like:
AAA
BBB
CCC
DDD
Which I transformed into:
list_1 = ['AAA', 'BBB', 'CCC', ...]
And I need to compare it with another text file with 2221545 entries that looks like:
AAA,.ADJ UK
AAA,.N UK
AAA,.N ES
B,.ADV UK
BB,.ADV UK
BBB,.N IT
Which I transformed into:
list_2 = ['AAA\tADJ\tUK', 'AAA\tN\tUK', 'AAA\tN\tES', 'B\tADV\UK', 'BB\tADV\tUK', ...]
So I have to get a dict that looks like this:
result_dict = {'AAA':[[UK, ADJ, N], [ES,N]], 'BBB':[[IT,N]], ...}
Due to the size of the second list, if we compare the entries one by one the time complexity will be O(11965*2221545). (Am I getting in right?)
And because I have to get the entire entry, I cannot use set to compare them. Is there any efficient way to get the job done?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to find a Spell Checker in Python which can be used in different languages apart from English, I am specially interested in Portuguese. By doing my research, the best I have found so far is the Bing Spell Check API for Python, by Microsoft.
However, to use it you need an Azure account in order to get the keys. I was wondering if there exists any other alternative where I can get the spell check with its suggestions by free. So far I have found PyEnchant
library, but it is out-of-date, and autocorrection library, which only supports English language.
I have also found Peter Norvig's code, but I was wondering if there is any other implementation for spell checking that have been tested in other languages.
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to use tensorflow.SequenceExample to store my features for something like a question-answer system, which are described below.
Given a question text, for instance, "how far is home". I would like to treat it as a sequence, and represent each word using a sparse representation. This is not a one-hot encoding. Each word has multiple Boolean features.
how -> [ 1 0 0 0 1] -> [1,5]
far -> [ 0 1 1 0 0] -> [2,3]
is -> [ 1 1 0 0 1] -> [1,2,5]
home-> [ 0 0 1 1 0] -> [3,4]
My text is now represented as: [[1,5],[2,3],[1,2,5],[3,4]]
Similarly, I have another text say answer text which has a similar representation of list-of-lists.
How do I write this in tensorflow's TFRecord format? I've tried it in the code below. What I know of to be an error is that I am sending an int64list to a function that expects only a single int64 value.
Did anyone have any success in representing such data?
import tensorflow as tf
example = {
'query': [[123, 543, 234, 2322],
[133, 243, 233, 256, 4332],
[232, 356, 632],
[153, 143, 231, 456]],
'document': [[1156, 12322],
[2133, 14332],
[1143, 1343, 1232, 1356, 1632],
[1153, 1143]],
'label': 1
}
tmp_filename = 'tf.tmp'
def make_example(example):
"""
Makes a single example from Python lists that follows the
format of tf.train.SequenceExample.
"""
query_features = example['query']
keyword_features = example['document']
example_sequence = tf.train.SequenceExample()
example_sequence.context.feature["query_length"].int64_list.value.append(len(query_features))
example_sequence.context.feature["keyword_length"].int64_list.value.append(len(keyword_features))
query = example_sequence.feature_lists.feature_list["query"]
document = example_sequence.feature_lists.feature_list["document"]
for feat in query_features:
print("Appending: ", feat)
#query.feature.add().int64_list.value.append(feat)
query.feature.add().list.value.append(feat)
for feat in keyword_features:
document.feature.add().int64_list.value.append(feat)
return example_sequence
# Write all examples into a TFRecords file
def save_tf(filename):
with open(filename, 'w') as fp:
writer = tf.python_io.TFRecordWriter(fp.name)
ex = make_example(example)
writer.write(ex.SerializeToString())
writer.close()
#
def read_and_decode_single_example(filename):
filename_queue = tf.train.string_input_producer([filename],
num_epochs=None)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
context_features = {
"length": tf.FixedLenFeature([], dtype=tf.int64)
}
sequence_features = {
"query": tf.VarLenFeature([], dtype=tf.int64),
"document": tf.VarLenFeature([], dtype=tf.int64)
}
return serialized_example, context_features, sequence_feature
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to apply Sentiment Analysis (predicting negative and positive tweets) on a relatively large Dataset (10000 rows). So far, I achieved only ~73% accuracy using Naive Bayes and my method called "final" shown below to extract features. I want to add PoS to help with the classification, but am completely unsure how to implement it. I tried writing a simple function called "pos" (which I posted below) and attempted using the tags on my cleaned dataset as features, but only got around 52% accuracy this way.. Can anyone lead me in the right direction to implement PoS for my model? Thank you.
def pos(word):
return [t for w, t in nltk.pos_tag(word)]
def final(text):
"""
I have code here to remove URLs,hashtags,
stopwords,usernames,numerals, and punctuation.
"""
#lemmatization
finished = []
for x in clean:
finished.append(lem.lemmatize(x))
return finished
| 1 | 1 | 0 | 0 | 0 | 0 |
I have tried two ways of removing stopwords, both of which I run into issues:
Method 1:
cachedStopWords = stopwords.words("english")
words_to_remove = """with some your just have from it's /via & that they your there this into providing would can't"""
remove = tu.removal_set(words_to_remove, query)
remove2 = tu.removal_set(cachedStopWords, query)
In this case, only the first remove function works. remove2 doesn't work.
Method 2:
lines = tu.lines_cleanup([sentence for sentence in sentence_list], remove=remove)
words = '
'.join(lines).split()
print words # list of words
output looks like this ["Hello", "Good", "day"]
I try to remove stopwords from words. This is my code:
for word in words:
if word in cachedStopwords:
continue
else:
new_words='
'.join(word)
print new_words
The output looks like this:
H
e
l
l
o
Cant figure out what is wrong with the above 2 methods. Please advice.
| 1 | 1 | 0 | 0 | 0 | 0 |
Been following the documentation here and as well as in this link: Machine Learning Gensim Tutorial and I'm at a complete loss for why this is happening. After tokenizing and lemmatizing my sentences, I put the sentences through a phraser, created a Dictionary, and inserted all the right variables into the model. Here is a sampling of my code:
tokens = [[euid, sent, gensim.parsing.preprocessing.preprocess_string(sent.lower(), filters=[strip_punctuation,
strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short, wordnet_stem])] for sent in sentences]
#these filters are all default gensim filters except for wordnet_stem, which uses a WordNetLemmatizer
bigram = gensim.models.Phrases(bag_of_words)
bigram_mod = gensim.models.phrases.Phraser(bigram)
Sample token list looks like this: ['beautiful', 'Manager', 'tree', 'caring', 'great_place'] (completely made-up list)
texts = [bigram_mod[t] for t in bag_of_words]
id2word = corpora.Dictionary(texts)
sent_wordfreq = [id2word.doc2bow(sent) for sent in texts]
lda_model = gensim.models.ldamodel.LdaModel(corpus=sent_wordfreq,
id2word=id2word,
num_topics=5,
update_every=1,
alpha='auto',
per_word_topics=True)
Here are the topics I'm getting:
[(0, 'nan*"discovered" + nan*"gained" + nan*"send" + ...
(1, 'nan*"discovered" + nan*"gained" + nan*"send" + ...
and this continues on 3 more times
So not only are all the topics the same, each's weight is nan. What could be the issue?
| 1 | 1 | 0 | 0 | 0 | 0 |
Hey I am working with bag of words and I am trying to implement so suppose I have the corpus below but I don't want to use print( vectorizer.fit_transform(corpus).todense() ) as a vocabulary instead I have one create which goes like
{u'all': 0, u'sunshine': 1, u'some': 2, u'down': 3, u'reason': 4}
How can I use this vocabulary to generate the matrix?
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'All my cats in a row',
'When my cat sits down, she looks like a Furby toy!',
'The cat from outer space',
'Sunshine loves to sit like this for some reason.'
]
vectorizer = CountVectorizer()
print( vectorizer.fit_transform(corpus).todense() )
print( vectorizer.vocabulary_ )
| 1 | 1 | 0 | 1 | 0 | 0 |
I'm running duckling.py to do some entity extractions.
Can someone please advise whats causing the error stated below?
Someone suggested that this resolved the issue for them, but i couldnt get it to install (maybe because i'm using windows??)
"conda install libgcc"
Here is code causing the traceback:
def _start_jvm(self, minimum_heap_size, maximum_heap_size):
jvm_options = [
'-Xms{minimum_heap_size}'.format(minimum_heap_size = minimum_heap_size),
'-Xmx{maximum_heap_size}'.format(maximum_heap_size = maximum_heap_size),
'-Djava.class.path={classpath}'.format(
classpath = self._classpath)
]
if not jpype.isJVMStarted():
jpype.startJVM(
jpype.getDefaultJVMPath(),
* jvm_options
)
Here is the traceback:
Traceback(most recent call last):
File "<ipython-input-5-e568931e00a0>", line 1, in < module > runfile('C:/Users/user/.spyder-py3/chatbot/Outlook/intent finder.py', wdir ='C:/Users/user/.spyder-py3/chatbot/Outlook')
File "C:\Users\user\AppData\Local\Continuum\anaconda3\lib\site packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace)
File "C:\Users\user\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/user/.spyder-py3/chatbot/Outlook/intent finder.py", line 19, in < module > numbersmodel = Interpreter.load(r 'C:\Users\user\.spyder-py3\chatbot\Outlook
umbers\default\model')
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\model.py", line 276, in load skip_validation)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\model.py", line 303, in create model_metadata, ** context)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\components.py", line 400, in load_component cached_component, ** context)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\registry.py", line 131, in load_component_by_name return component_clz.load(model_dir, metadata, cached_component, ** kwargs)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\extractors\duckling_extractor.py", line 194, in load duckling = cls.create_duckling_wrapper(language)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\rasa_nlu\extractors\duckling_extractor.py", line 108, in create_duckling_wrapper return DucklingWrapper(language = language)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\duckling\wrapper.py", line 35, in __init__maximum_heap_size = maximum_heap_size)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\duckling\duckling.py", line 44, in __init__self._start_jvm(minimum_heap_size, maximum_heap_size)
File "C:\Users\user\.spyder-py3\chatbot\Outlook\duckling\duckling.py", line 67, in _start_jvm if not jpype.isJVMStarted():
AttributeError: module 'jpype' has no attribute 'isJVMStarted'
| 1 | 1 | 0 | 0 | 0 | 0 |
I am working on a project to classify customer feedback into buckets based on the topic of the feedback comment. So , I need to classify the sentence into one of the topics among a list of pre-defined topics.
For example :
"I keep getting an error message every time I log in" has to be tagged with "login" as the topic.
"make the screen more colorful" has to be tagged with "improvements" as the topic.
So the topics are very specific to the product and the context.
LDA doesn't seem to work for me(correct me if i'm wrong). It detects the topics in a general sense like "Sports" , "Politics" , "Technology" etc. But I need to detect specific topics as mentioned above.
Also , I don't have labelled data for training. All I have is the comments.
So supervised learning approach doesn't look like an option.
What I have tried so far:
I trained a gensim model with google news corpus (its about 3.5 gb).
I am cleaning the sentence by removing stop words , punctuation marks etc.
I am finding , to what topic among the set of topics each word is closest to and tag the word to that topic. With an idea that the sentence might contain more words closer to the topic it is referring to than not , I am picking up the topic(s) to which maximum number of words in the sentence is mapped to.
For example:
If 3 words in a sentence is mapped to "login" topic and 2 words in the sentence is mapped to "improvement" topic , I am tagging the sentence to "login" topic.
If there is a clash between the count of multiple topics , I return all the topics with the maximum count as the topic list.
This approach is giving me fair results. But its not good enough.
What will be the best approach to tackle this problem?
| 1 | 1 | 0 | 1 | 0 | 0 |
I am trying to filter (and consequently change) certain rows in pandas that depend on values in other columns. Say my dataFrame looks like this:
SENT ID WORD POS HEAD
1 1 I PRON 2
1 2 like VERB 0
1 3 incredibly ADV 4
1 4 brown ADJ 5
1 5 sugar NOUN 2
2 1 Here ADV 2
2 2 appears VERB 0
2 3 my PRON 5
2 4 next ADJ 5
2 5 sentence NOUN 0
The structure is such that the 'HEAD' column points at the index of the word on which the row is dependent on. For example, if 'brown' depends on 'sugar' then the head of 'brown' is 4, because the index of 'sugar' is 4.
I need to extract a df of all the rows in which the POS is ADV whose head's POS VERB, so 'Here' will be in the new df but not 'incredibly', (and potentially make changes to their WORD entry).
At the moment I'm doing it with a loop, but I don't think it's the pandas way and it also creates problems further down the road. Here is my current code (the split("-") is from another story - ignore it):
def get_head(df, dependent):
head = dependent
target_index = int(dependent['HEAD'])
if target_index == 0:
return dependent
else:
if target_index < int(dependent['INDEX']):
# 1st int in cell
while (int(head['INDEX'].split("-")[0]) > target_index):
head = data.iloc[int(head.name) - 1]
elif target_index > int(dependent['INDEX']):
while int(head['INDEX'].split("-")[0]) < target_index:
head = data.iloc[int(head.name) + 1]
return head
A difficulty I had when I wrote this function is that I didn't (at the time) have a column 'SENTENCE' so I had to manually find the nearest head. I hope that adding the SENTENCE column should make things somewhat easier, though it is important to note that as there are hundreds of such sentences in the df, simply searching for an index '5' won't do, since there are hundreds of rows where df['INDEX']=='5'.
Here is an example of how I use get_head():
def change_dependent(extract_col, extract_value, new_dependent_pos, head_pos):
name = 0
sub_df = df[df[extract_col] == extract_value] #this is another condition on the df.
for i, v in sub_df.iterrows():
if (get_head(df, v)['POS'] == head_pos):
df.at[v.name, 'POS'] = new_dependent_pos
return df
change_dependent('POS', 'ADV', 'ADV:VERB', 'VERB')
Can anyone here think of a more elegant/efficient/pandas way in which I can get all the ADV instances whose head is VERB?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am using some text for some NLP analyses. I have cleaned the text taking steps to remove non-alphanumeric characters, blanks, duplicate words and stopwords, and also performed stemming and lemmatization:
from nltk.tokenize import word_tokenize
import nltk.corpus
import re
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import pandas as pd
data_df = pd.read_csv('path/to/file/data.csv')
stopwords = nltk.corpus.stopwords.words('english')
stemmer = SnowballStemmer('english')
lemmatizer = WordNetLemmatizer()
# Function to remove duplicates from sentence
def unique_list(l):
ulist = []
[ulist.append(x) for x in l if x not in ulist]
return ulist
for i in range(len(data_df)):
# Convert to lower case, split into individual words using word_tokenize
sentence = word_tokenize(data_df['O_Q1A'][i].lower()) #data['O_Q1A'][i].split(' ')
# Remove stopwords
filtered_sentence = [w for w in sentence if not w in stopwords]
# Remove duplicate words from sentence
filtered_sentence = unique_list(filtered_sentence)
# Remove non-letters
junk_free_sentence = []
for word in filtered_sentence:
junk_free_sentence.append(re.sub("[^\w\s]", " ", word)) # Remove non-letters, but don't remove whitespaces just yet
#junk_free_sentence.append(re.sub("/^[a-z]+$/", " ", word)) # Take only alphabests
# Stem the junk free sentence
stemmed_sentence = []
for w in junk_free_sentence:
stemmed_sentence.append(stemmer.stem(w))
# Lemmatize the stemmed sentence
lemmatized_sentence = []
for w in stemmed_sentence:
lemmatized_sentence.append(lemmatizer.lemmatize(w))
data_df['O_Q1A'][i] = ' '.join(lemmatized_sentence)
But when I display the top 10 words (according to some criteria), I still get some junk like:
ask
much
thank
work
le
know
via
sdh
n
sy
t
n t
recommend
never
Out of these top 10 words, only 5 are sensible (ask, know, recommend, thank and work). What more do I need to do to retain only meaningful words?
| 1 | 1 | 0 | 1 | 0 | 0 |
Say I have this sentence: I am a boy. I want to find out the Part of Speech of each word in the sentence. This is my code:
import nltk
sentence = 'I am a good boy'
for word in sentence:
print(word)
print(nltk.pos_tag(word))
But this produces the following output:
I
[('I', 'PRP')]
[(' ', 'NN')]
a
[('a', 'DT')]
m
[('m', 'NN')]
[(' ', 'NN')]
a
[('a', 'DT')]
[(' ', 'NN')]
g
[('g', 'NN')]
o
[('o', 'NN')]
o
[('o', 'NN')]
d
[('d', 'NN')]
[(' ', 'NN')]
b
[('b', 'NN')]
o
[('o', 'NN')]
y
[('y', 'NN')]
So, I tried to do this instead:
sentence = 'I am a good boy'
for word in sentence.split(' '):
print(word)
print(nltk.pos_tag(word))
And this produces the following output:
I
[('I', 'PRP')]
am
[('a', 'DT'), ('m', 'NN')]
a
[('a', 'DT')]
good
[('g', 'NN'), ('o', 'MD'), ('o', 'VB'), ('d', 'NN')]
boy
[('b', 'NN'), ('o', 'NN'), ('y', 'NN')]
Why is it finding the PoS for each letter instead of each word? And how do I fix this?
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a code for dependency parsing which gives output in the form of arcs. Is there any other way to display the parse tree for a paragraph? Because for a paragraph, the parse tree is huge. Is there a better way to display the parse tree for a paragraph?
| 1 | 1 | 0 | 0 | 0 | 0 |
First of all, I realize from a methodological standpoint why your loss function must be dependent on the output of a neural network. This question comes more from an experiment I've been doing while trying to understand Keras and Tensorflow a bit better. Consider the following:
input_1 = Input((5,))
hidden_a = Dense(2)(input_1)
output = Dense(1)(hidden_a)
m3 = Model(input_1, output)
def myLoss (y_true, y_pred):
return K.sum(hidden_a) # (A)
#return K.sum(hidden_a) + 0*K.sum(y_pred) # (B)
m3.compile(optimizer='adam', loss=myLoss)
x = np.random.random(size=(10,5))
y = np.random.random(size=(10,1))
m3.fit(x,y, epochs=25)
This code induces:
ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
but it runs if you swap line A for line B despite the fact that nothing has changed numerically.
The former case seems like it should be perfectly fine to me. The computation graph is well defined and everything should be differentiable in terms of the loss. But it seems that Keras requires y_pred to be in the loss function somehow regardless of whether or not it has any effect.
Thanks!
| 1 | 1 | 0 | 1 | 0 | 0 |
Gensim's Word2Vec model takes as an input a list of lists with the inner list containing individual tokens/words of a sentence. As I understand Word2Vec is used to "quantify" the context of words within a text using vectors.
I am currently dealing with a corpus of text that has already been split into individual tokens and no longer contains an obvious sentence format (punctuation has been removed). I was wondering how should I input this into the Word2Vec model?
Say if I simply split the corpus into "sentences" of uniform length (10 tokens per sentence for example), would this be a good way of inputting the data into the model?
Essentially, I am wondering how the format of the input sentences (list of lists) affects the output of Word2Vec?
| 1 | 1 | 0 | 0 | 0 | 0 |
I'd present my model, but I've seen this result across the board. As en example, I'm training a model now where with use straight mse, the loss bottomed out at 0.0160. But when I used 100 * mse, the loss is now shooting down below 0.2, where I would have expected it to bottom out around 1.6. Does anybody have any idea why training Keras models might be sensitive to multiplying losses by scalars?
EDIT: And just to clarify, when this has happened to me, the model does end up doing better so it's not just a numerical quirk.
EDIT2: I've been asked to provide some example code, so I will. I'm working with using a convolutional variational autoencoder as a generative model. Here is my custom loss function:
def vae_loss (input_image, decoder_output):
mse_loss = mse(input_image, decoder_output)
kl_loss = - 0.5 * (K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=[-1,-2,-3]))
return mse_loss # (A)
#return 100 * mse_loss # (B)
I realize that this doesn't use kl_loss, this is just meant as an experiment. I'm compiling the model with:
vae.compile(optimizer='adadelta', loss=vae_loss)
and fitting with:
vae.fit_generator(random_crop(data[:500,:,:,:], 128, 128),
validation_data=random_crop(data[500:,:,:,:], 128, 128),
shuffle=True, steps_per_epoch=64, epochs=5, validation_steps=50)
Using A as the loss function converges to a loss of 0.0160. If using B caused the model to converge to the identical solution (and I would expect it to since multiplying by a scalar doesn't change the location of local minima), I would expect it to converge to a loss of 1.60, 100 times A. But it doesn't. In fact, B does significantly better than A both in terms of loss and in terms of the qualitative products of the network.
| 1 | 1 | 0 | 1 | 0 | 0 |
trying to comprehend tensorflow strided_slice and slice
x = tf.constant(np.array( [[[111, 112, 113], [121, 122, 123]],
[[211, 212, 213], [221, 222, 223]],
[[311, 312, 313], [321, 322, 323]]]))
with tf.Session() as sess:
print("tf.shape ------------------")
print(sess.run(tf.shape(x)))
print("tf.slice ------------------------")
print(sess.run((tf.slice(x, [1, 0, 0], [2, 1, 3]) )))
print("tf.strided_slice ------------------------")
print(sess.run(tf.strided_slice(x, [1, 0, 0], [2, 1, 3], [1, 1, 1])))
print(sess.run(tf.strided_slice(x, [1, -1, 0], [2, -3, 3], [1, -1, 1])))
print(sess.run(x[1,-1,0]))
print(sess.run(x[2,-3,3]))
output
tf.shape ------------------
[3 2 3]
tf.slice ------------------------
[[[211 212 213]]
[[311 312 313]]]
tf.strided_slice ------------------------
[[[211 212 213]]]
[[[221 222 223]
[211 212 213]]]
221
ValueError: slice index -1 of dimension 1 out of bounds. for 'strided_slice_8' (op: 'StridedSlice') with input shapes: [3,2,3], [3], [3], [3] and with computed input tensors: input[1] = <2 -3 3>, input[2] = <3 -2 4>, input[3] = <1 1 1>.
for tf.slice i understand we have to mentions slice sizes in each dimension and hence out of range values makes sense. but in strided slice the end is a tensor index in the tensor itself, how come out of size value is valid.
Example is taken from
https://www.tensorflow.org/api_docs/python/tf/strided_slice
Trying to implement folding layer part from paper A Convolutional Neural Network for Modelling Sentences
In the formulation of the network so far, feature detectors applied to
an individual row of the sentence matrix s can have many orders and
create complex dependencies across the same rows in multiple feature
maps. Feature detectors in different rows, however, are independent of
each other until the top fully connected layer. Full dependence
between different rows could be achieved by making M in Eq. 5 a full
matrix instead of a sparse matrix of diagonals. Here we explore a
simpler method called folding that does not introduce any additional
parameters. After a convolutional layer and before (dynamic) k-max
pooling, one just sums every two rows in a feature map component-wise.
For a map of d rows, folding returns a map of d/2 rows, thus halving
the size of the representation. With a folding layer, a feature
detector of the i-th order depends now on two rows of feature values
in the lower maps of order i − 1. This ends the description of the
DCNN.
| 1 | 1 | 0 | 0 | 0 | 0 |
I developed a simple extractor of passport number from words (for example, input - 'one hundred thirty five thirty five zero zero gets output - 1353500)
but how can I filter out unrelevant words like 'ok', 'mhm' and so on?
for example human can say 'ok it is 1353500' and bot will extract some meaningless numbers from 'ok', 'it', 'is' and it is bad. The question is how to ignore those non-number words?
| 1 | 1 | 0 | 1 | 0 | 0 |
This is my code to read text from a CSV file and convert all the words in a column of it into singular form from plural:
import pandas as pd
from textblob import TextBlob as tb
data = pd.read_csv(r'path\to\data.csv')
for i in range(len(data)):
blob = tb(data['word'][i])
singular = blob.words.singularize() # This makes singular a list
data['word'][i] = ''.join(singular) # Converting the list back to a string
But this code has been running for minutes now (and possibly keep running for hours, if I don't stop it?)! Why is that? When I checked for few words individually, the conversion happens instantly - doesn't take any time at all. There are only 1060 rows (words to convert) in the file.
EDIT: It finished running in about 10-12 minutes.
Here's some sample data:
Input:
word
development
investment
funds
slow
company
commit
pay
claim
finances
customers
claimed
insurance
comment
rapid
bureaucratic
affairs
reports
policyholders
detailed
Output:
word
development
investment
fund
slow
company
commit
pay
claim
finance
customer
claimed
insurance
comment
rapid
bureaucratic
affair
report
policyholder
detailed
| 1 | 1 | 0 | 0 | 0 | 0 |
Here I'm working with a Sentiment Classification problem, where I have to predict whether the tweets are positive, negative or neutral. Here's a glimpse of my dataset:
tweet_id airline_sentiment_confidence negativereason negativereason_confidence airline name retweet_count text tweet_created tweet location user_timezone airline_sentiment
Tr_tweet_1 1.000 NaN NaN Virgin America 0 tweets date Location Time Positive
Tr_tweet_2 0.3846 NaN 0.7033 Virgin America 0 tweets date Location Time Negative
Tr_tweet_3 0.6837 Bad flight 0.3342 Virgin America 0 tweets date Location Time Negative
Tr_tweet_4 1.000 Can't tell 1.000 Virgin America 0 tweets date Location Time Neutral
Tr_tweet_5 1.000 NaN NaN Virgin America 0 tweets date Location Time Neutral
However text is the column which I'm fitting in my TfIdf_Vectorizer and using logreg to predict the sentiment. However I'm getting a very low accuracy of ~68%, which turns out to be a pure NLP problem. However the other features will surely increase my accuracy if I can somehow use them.
I'm interested in knowing how can I combine the other numerical as well as textual columns like negativereason as features with my text column, to increase my accuracy.
Or is there any method of stacking that can be done here? Like combining the predictions of Tfidf and then once again doing prediction with rest numerical columns?
TL;DR How to deal with numerical as well as textual columns as features to make a good prediction?
| 1 | 1 | 0 | 1 | 0 | 0 |
I'm try to understanding what convolution neural network does in NLP.
For example, my input sentence matrix has dimension (100,200). Here 100 is the length of my sentence, 200 is the dimension of word embedding.
Then I used convolution layer to extract feature. In Keras, something like Conv1D(filters=128, kernel_size=3, padding='same', activation='tanh', strides=1).
But why the output dimension is (100,128)? I can understand the first number, because I use padding same, and stride 1, so the dimension should be the same. But why the second dimension is 128, shouldn't it be 200*128? What does the kernel actually look like? I'm assuming it only scan along the sentence, but why the embedding dimension get lost, the kernel just summed it up?
I add a picture to illustrate it better. If it is a 1D kernel, and do convolution over the word sequence, why after convolution the word embedding dimension becomes 1(shown in picture)? That doesn't make sense to me.
| 1 | 1 | 0 | 0 | 0 | 0 |
In German, every job has a feminine and a masculine version. The feminine one is derived from the masculine one by adding an "-in" suffix. In the plural form, this turns into "-innen".
Example:
| English | German
------+------------------+-----------------------
masc. | teacher doctor | Lehrer Arzt
fem. | teacher doctor | Lehrerin Ärztin
masc. | teachers doctors | Lehrer Ärzte
fem. | teachers doctors | Lehrerinnen Ärztinnen
Currently, I'm using NLTK's nltk.stem.snowball.GermanStemmer.
It returns these stems:
Lehrer -> lehr | Arzt -> arzt
Lehrerin -> lehrerin | Ärztin -> arztin
Lehrer -> lehr | Ärzte -> arzt
Lehrerinnen -> lehrerinn | Ärztinnen -> arztinn
Is there a way to make this stemmer return the same stems for all four versions, feminine and masculine ones? Alternatively, is there any other stemmer doing that?
Update
I ended up adding "-innen" and "-in" as the first entries in the step 1 suffix-tuple like so:
stemmer = GermanStemmer()
stemmer._GermanStemmer__step1_suffixes = ("innen", "in") + stemmer._GermanStemmer__step1_suffixes
This way all of the above words are stemmed to lehr and arzt respectively. Also, all other "job-forms" that I tried so far are stemmed correctly, meaning masculine and feminine forms have the same stem. Also, if the "job-form" is derived from a verb, like Lehrer/in, they have the same stem as the verb.
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to connect database with api.ai to add question suggestion for my bot, but can not find any example, I need code example in javascript or python please
| 1 | 1 | 0 | 0 | 0 | 0 |
I am running the cort coreference resolution from this github repo. Using the syntax to run the system on raw input text as follows:
cort-predict-raw -in *.txt \
-model model.obj \
-extractor cort.coreference.approaches.mention_ranking.extract_substructures \
-perceptron cort.coreference.approaches.mention_ranking.RankingPerceptron \
-clusterer cort.coreference.clusterer.all_ante \
-corenlp /home/kenden/deeshacodes/corenlp \
I get the following error :-
Exception in thread "main" edu.stanford.nlp.util.ReflectionLoading$ReflectionLoadingException: Error creating edu.stanford.nlp.time.TimeExpressionExtractorImpl
at edu.stanford.nlp.util.ReflectionLoading.loadByReflection(ReflectionLoading.java:40)
at edu.stanford.nlp.time.TimeExpressionExtractorFactory.create(TimeExpressionExtractorFactory.java:57)
at edu.stanford.nlp.time.TimeExpressionExtractorFactory.createExtractor(TimeExpressionExtractorFactory.java:38)
at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.<init>(NumberSequenceClassifier.java:86)
at edu.stanford.nlp.ie.NERClassifierCombiner.<init>(NERClassifierCombiner.java:132)
at edu.stanford.nlp.pipeline.AnnotatorImplementations.ner(AnnotatorImplementations.java:121)
at edu.stanford.nlp.pipeline.AnnotatorFactories$6.create(AnnotatorFactories.java:273)
at edu.stanford.nlp.pipeline.AnnotatorPool.get(AnnotatorPool.java:152)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.construct(StanfordCoreNLP.java:451)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:154)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:150)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:137)
at corenlp.JsonPipeline.initializeCorenlpPipeline(JsonPipeline.java:206)
at corenlp.SocketServer.main(SocketServer.java:102)
Caused by: edu.stanford.nlp.util.MetaClass$ClassCreationException: MetaClass couldn't create public edu.stanford.nlp.time.TimeExpressionExtractorImpl(java.lang.String,java.util.Properties) with args [sutime, {}]
at edu.stanford.nlp.util.MetaClass$ClassFactory.createInstance(MetaClass.java:237)
at edu.stanford.nlp.util.MetaClass.createInstance(MetaClass.java:382)
at edu.stanford.nlp.util.ReflectionLoading.loadByReflection(ReflectionLoading.java:38)
... 13 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:466)
at edu.stanford.nlp.util.MetaClass$ClassFactory.createInstance(MetaClass.java:233)
... 15 more
Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at de.jollyday.util.CalendarUtil.<init>(CalendarUtil.java:42)
at de.jollyday.HolidayManager.<init>(HolidayManager.java:66)
at de.jollyday.impl.DefaultHolidayManager.<init>(DefaultHolidayManager.java:46)
at edu.stanford.nlp.time.JollyDayHolidays$MyXMLManager.<init>(JollyDayHolidays.java:148)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:466)
at java.base/java.lang.Class.newInstance(Class.java:556)
at de.jollyday.caching.HolidayManagerValueHandler.instantiateManagerImpl(HolidayManagerValueHandler.java:60)
at de.jollyday.caching.HolidayManagerValueHandler.createValue(HolidayManagerValueHandler.java:41)
at de.jollyday.caching.HolidayManagerValueHandler.createValue(HolidayManagerValueHandler.java:13)
at de.jollyday.util.Cache.get(Cache.java:51)
at de.jollyday.HolidayManager.createManager(HolidayManager.java:168)
at de.jollyday.HolidayManager.getInstance(HolidayManager.java:148)
at edu.stanford.nlp.time.JollyDayHolidays.init(JollyDayHolidays.java:57)
at edu.stanford.nlp.time.Options.<init>(Options.java:90)
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.init(TimeExpressionExtractorImpl.java:44)
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.<init>(TimeExpressionExtractorImpl.java:39)
... 20 more
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:532)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:186)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:473)
... 39 more
I have tried corenlp version 3.5.2, 3.6.0 as well as 3.7.0 but nothing works. Where would I be going wrong?
| 1 | 1 | 0 | 0 | 0 | 0 |
I want to use RFTagger (http://www.cis.uni-muenchen.de/~schmid/tools/RFTagger/) in my Pyhton code. The only way that I got it to work is like this:
file = open("RFTagger/temp.txt", "w")
file.write(text)
file.close()
test_tagged = check_output(["cmd/rftagger-german", "temp.txt"], cwd="RFTagger").decode("utf-8")
Is there an easier / faster way? Or is there a similar library that can give the same output? I especially need it for German.
Thank you for your help :)
| 1 | 1 | 0 | 0 | 0 | 0 |
I am learning to use Keras functional API and I have managed to build and compile a model. But when I call the model.fit passing the data X and labels y, I got an error. It seems I still haven't got the idea of how it works.
The task is classifying sentences into 6 types, and the code goes:
X_ = ... # shape: (2787, 100) each row a sentence and each column a feature
y_= ... # shape: (2787,)
word_matrix_weights= ... # code to initiate a lookup matrix for vocabulary embeddings. shape: (9825,300)
deep_inputs = Input(shape=(100,))
embedding = Embedding(9825, 300, input_length=100,
weights=[word_matrix_weights], trainable=False)(deep_inputs)
flat = Flatten()(embedding)
hidden = Dense(6, activation="softmax")(flat)
model = Model(inputs=deep_inputs, outputs=hidden)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x=X_,y=y_,epochs=100, batch_size=10, verbose=0) #error here
The last line generates an error:
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1555, in fit
batch_size=batch_size)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1413, in _standardize_user_data
exception_prefix='target')
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 154, in _standardize_input_data
str(array.shape))
ValueError: Error when checking target: expected dense_1 to have shape (None, 6) but got array with shape (2878, 1)
Any suggestions, please?
| 1 | 1 | 0 | 1 | 0 | 0 |
I am developing a application in python which gives job recommendation based on the resume uploaded. I am trying to tokenize resume before processing further. I want to tokenize group of words. For example Data Science is a keyword when i tokenize i will get data and science separately. How to overcome this situation. Is there any library which does these extraction in python?
| 1 | 1 | 0 | 0 | 0 | 0 |
I build a Keras model that has 2 branches, each taking a different feature representation for the same data. The task is classifying sentences into one of 6 classes.
I have tested my code up to model.fit that takes in a list containing the two input feature matrices as X. Everything works OK. But on prediction, when I pass the two input feature matrices for test data, an error is generated.
The code is as follows:
X_train_feature1 = ... # shape: (2200, 100) each row a sentence and each column a feature
X_train_feature2 = ... # shape: (2200, 13) each row a sentence and each column a feature
y_train= ... # shape: (2200,6)
X_test_feature1 = ... # shape: (587, 100) each row a sentence and each column a feature
X_test_feature2 = ... # shape: (587, 13) each row a sentence and each column a feature
y_test= ... # shape: (587,6)
model= ... #creating a model with 2 branches, see the image below
model.fit([X_train_feature1, X_train_feature2],y_train,epochs=100, batch_size=10, verbose=2) #Model trains ok
model.predict([X_test_feature1, X_test_feature2],y_test,epochs=100, batch_size=10, verbose=2) #error here
The model looks like this:
And the error is:
predictions = model.predict([X_test_feature1,X_test_feature2], y_test, verbose=2)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1748, in predict
verbose=verbose, steps=steps)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1290, in _predict_loop
batches = _make_batches(num_samples, batch_size)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 384, in _make_batches
num_batches = int(np.ceil(size / float(batch_size)))
TypeError: only length-1 arrays can be converted to Python scalars
I would really appreciate some help to understand the error and how to fix it.
| 1 | 1 | 0 | 1 | 0 | 0 |
I used scrapy to crawl several bullying forums and used the results as a dictionary.
What I'm trying to do now is extracting the keywords of a sentence, e.g. He harassed me in the chat, which would give the keywords Harassed and chat, and comparing these keywords to my dictionary of words and assigning a value to how relevant it is (which in this case would obviously provide a high value close to 1.0 since it is extremely relevant to bullying).
I've gotten the keyword extraction down, so right now I just need know how I can do the comparison.
I've taken a look at using pandas, scikit and nltk but they seem to work best for dictionaries with multiple fields, whereas I only have a bag of words.
Is there some NLP library out there that does this for me? If not, what would be the best way to go about this?
| 1 | 1 | 0 | 0 | 0 | 0 |
I've been following SentDex's video series regarding NLTK and Python, and have constructed a script which determines review-sentiment using various models, e.g. logistic regression. My worry is that I think SentDex's approach includes the test-set while determining words to be used for training, which is obviously not preferable (train/test split occurs after feature-selection).
(Edited in response to Mohammed Kashif's comments)
Full code:
import nltk
import numpy as np
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.classify import ClassifierI
from nltk.corpus import movie_reviews
from sklearn.naive_bayes import MultinomialNB
documents = [ (list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category) ]
all_words = []
for w in movie_reviews.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
def find_features(documents):
words = set(documents)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev, category) in documents]
np.random.shuffle(featuresets)
training_set = featuresets[:1800]
testing_set = featuresets[1800:]
MNB_classifier = SklearnClassifier(MultinomialNB())
MNB_classifier.train(training_set)
print("MNB_classifier accuracy:", (nltk.classify.accuracy(MNB_classifier, testing_set)) *100)
Already tried:
documents = [ (list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category) ]
np.random.shuffle(documents)
training_set = documents[:1800]
testing_set = documents[1800:]
all_words = []
for w in documents.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
def find_features(training_set):
words = set(training_set)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev, category) in training_set]
np.random.shuffle(featuresets)
training_set = featuresets
testing_set = testing_set
MNB_classifier = SklearnClassifier(MultinomialNB())
MNB_classifier.train(training_set)
print("MNB_classifier accuracy:", (nltk.classify.accuracy(MNB_classifier, testing_set)) *100)
Yields the error:
Traceback (most recent call last):
File "", line 34, in
print("MNB_classifier accuracy:", (nltk.classify.accuracy(MNB_classifier, testing_set)) *100)
File "C:\ProgramData\Anaconda3\lib\site-packages
ltk\classify\util.py", line 87, in accuracy
results = classifier.classify_many([fs for (fs, l) in gold])
File "C:\ProgramData\Anaconda3\lib\site-packages
ltk\classify\scikitlearn.py", line 85, in classify_many
X = self._vectorizer.transform(featuresets)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 291, in transform
return self._transform(X, fitting=False)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 166, in _transform
for f, v in six.iteritems(x):
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\externals\six.py", line 439, in iteritems
return iter(getattr(d, _iteritems)(**kw))
AttributeError: 'list' object has no attribute 'items'
| 1 | 1 | 0 | 1 | 0 | 0 |
I have a trained Word2vec model using Python's Gensim Library. I have a tokenized list as below. The vocab size is 34 but I am just giving few out of 34:
b = ['let',
'know',
'buy',
'someth',
'featur',
'mashabl',
'might',
'earn',
'affili',
'commiss',
'fifti',
'year',
'ago',
'graduat',
'21yearold',
'dustin',
'hoffman',
'pull',
'asid',
'given',
'one',
'piec',
'unsolicit',
'advic',
'percent',
'buy']
Model
model = gensim.models.Word2Vec(b,min_count=1,size=32)
print(model)
### prints: Word2Vec(vocab=34, size=32, alpha=0.025) ####
if I try to get the similarity score by doing model['buy'] of one the words in the list, I get the
KeyError: "word 'buy' not in vocabulary"
Can you guys suggest me what I am doing wrong and what are the ways to check the model which can be further used to train PCA or t-sne in order to visualize similar words forming a topic? Thank you.
| 1 | 1 | 0 | 0 | 0 | 0 |
I am using PyPDF2 to read PDF files in python. While it works well for languages in English and European languages (with alphabets in english), the library fails to read Asian languages like Japanese and Chinese. I tried encode('utf-8'), decode('utf-8') but nothing seems to work. It just prints a blank string on extraction of the text.
I have tried other libraries like textract and PDFMiner but no success yet.
When I copy the text from PDF and paste it on a notebook, the characters turn into some random format text (probably in a different encoding).
def convert_pdf_to_text(filename):
text = ''
pdf = PyPDF2.PdfFileReader(open(filename, "rb"))
if pdf.isEncrypted:
pdf.decrypt('')
for page in pdf.pages:
text = text + page.extractText()
return text
Can anyone point me in the right direction?
| 1 | 1 | 0 | 0 | 0 | 0 |
How do I make "First word in the doc was [target word]" a feature?
Consider these two sentences:
example = ["At the moment, my girlfriend is Jenny. She is working as an artist at the moment.",
"My girlfriend is Susie. She is working as an accountant at the moment."]
If I were trying to measure relationship commitment, I'd want to be able to treat the phrase "at the moment" as a feature only when it shows up at the beginning like that.
I would love to be able to use regex's in the vocabulary...
phrases = ["^at the moment", 'work']
vect = CountVectorizer(vocabulary=phrases, ngram_range=(1, 3), token_pattern=r'\w{1,}')
dtm = vect.fit_transform(example)
But that doesn't seem to work.
I have also tried this, but get a 'vocabulary is empty' error...
CountVectorizer(token_pattern = r"(?u)^currently")
What's the right way to do this? Do I need a custom vectorizer? Any simple tutorials you can link me to? This is my first sklearn project, and I've been Googling this for hours. Any help much appreciated!
| 1 | 1 | 0 | 0 | 0 | 0 |
I've been using NLTK in python for doing sentiment analysis, it only has positive, neutral and negative class, what if we want to do sentiment analysis and having a number to show how much a sentence can be negative or positive. Sort of seeing it as a regression problem. Is there any pre-trained library out there to do so?
| 1 | 1 | 0 | 0 | 0 | 0 |
I built a supervised model to classify medical text data (my output predicts the positive or negative occurrence of a disease). The data is very imbalanced (130 positive cases compared to 1600 negative cases, which is understandable since the disease is rare). I first cleaned the data (removed unnecessary words, lemmatization, etc..) and applied POS afterwards. I then applied TfidfVectorizer and TfidfTransformer to this cleaned data. For classification, I tried both SVM and Random Forest, but achieved only 56% precision and 58% recall for the positive data even after tuning their parameters with GridSearchCV (I also made class_weight = 'balanced'). Does anyone have advice as to how to improve this low precision and recall? Thank you very much.
Here is my current Pipeline (obviously I only use one of the classifiers when I run it, but I displayed both just to show their parameters).
pipeline = Pipeline([
('vectors', TfidfVectorizer(ngram_range = (2,3),norm = 'l1', token_pattern = r"\w+\b\|\w+" ,min_df = 2, max_features = 1000).fit(data['final'])),
('classifier', RandomForestClassifier(n_estimators = 51, min_samples_split = 8, min_samples_leaf = 2, max_depth = 14, class_weight= 'balanced')),
('classifier', SVC(C = 1000, gamma = 1, class_weight = 'balanced', kernel='linear')),
])
| 1 | 1 | 0 | 1 | 0 | 0 |
I followed the NLTK book in using the confusion matrix but the confusionmatrix looks very odd.
#empirically exam where tagger is making mistakes
test_tags = [tag for sent in brown.sents(categories='editorial')
for (word, tag) in t2.tag(sent)]
gold_tags = [tag for (word, tag) in brown.tagged_words(categories='editorial')]
print nltk.ConfusionMatrix(gold_tags, test_tags)
Can anyone explain how to use the confusion matrix?
| 1 | 1 | 0 | 0 | 0 | 0 |
everybody. I'm trying to custom a co attention layer for a matching task. And there is an error confused me a lot.
model = Model(inputs=[ans_input, ques_input], outputs=output)
my program shutdown while running the code above. then it will throw
an error
AttributeError: 'Tensor' object has no attribute '_keras_history'
it means that my model cannot be a complete graph I guess. so I have tried lots of methods which I found at StackOverflow and other blogs. But all of these cannot work. :(
I will paste my model below. Thank you for helping me :)
import time
from keras.layers import Embedding, LSTM, TimeDistributed, Lambda
from keras.layers.core import *
from keras.layers.merge import concatenate
from keras.layers.pooling import GlobalMaxPooling1D
from keras.models import *
from keras.optimizers import *
from dialog.keras_lstm.k_call import *
from dialog.model.keras_himodel import ZeroMaskedEntries, logger
class Co_AttLayer(Layer):
def __init__(self, **kwargs):
# self.input_spec = [InputSpec(ndim=3)]
super(Co_AttLayer, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 2
assert len(input_shape[0]) == len(input_shape[1])
super(Co_AttLayer, self).build(input_shape)
def cosine_sim(self, x):
ans_ss = K.sum(K.square(x[0]), axis=2, keepdims=True)
ans_norm = K.sqrt(K.maximum(ans_ss, K.epsilon()))
ques_ss = K.sum(K.square(x[1]), axis=2, keepdims=True)
ques_norm = K.sqrt(K.maximum(ques_ss, K.epsilon()))
tr_ques_norm = K.permute_dimensions(ques_norm, (0, 2, 1))
tr_ques = K.permute_dimensions(x[1], (0, 2, 1))
ss = K.batch_dot(x[0], tr_ques, axes=[2, 1])
den = K.batch_dot(ans_norm, tr_ques_norm, axes=[2, 1])
return ss / den
def call(self, x, mask=None):
cosine = Lambda(self.cosine_sim)(x)
coqWij = K.softmax(cosine)
print(x[1].shape, coqWij.shape)
ai = K.dot(coqWij, x[1]) # (N A Q) (N Q L)
coaWij = K.softmax(K.permute_dimensions(cosine, (0, 2, 1)))
qj = K.dot(coaWij, x[0])
print(qj.shape, ai.shape)
return concatenate([ai, qj], axis=2)
def compute_output_shape(self, input_shape):
return input_shape
def build_QAmatch_model(opts, vocab_size=0, maxlen=300, embedd_dim=50, init_mean_value=None):
ans_input = Input(shape=(maxlen,), dtype='int32', name='ans_input')
ques_input = Input(shape=(maxlen,), dtype='int32', name='ques_input')
embedding = Embedding(output_dim=embedd_dim, input_dim=vocab_size, input_length=maxlen,
mask_zero=True, name='embedding')
dropout = Dropout(opts.dropout, name='dropout')
lstm = LSTM(opts.lstm_units, return_sequences=True, name='lstm')
hidden_layer = Dense(units=opts.hidden_units, name='hidden_layer')
output_layer = Dense(units=1, name='output_layer')
zme = ZeroMaskedEntries(name='maskedout')
ans_maskedout = zme(embedding(ans_input))
ques_maskedout = zme(embedding(ques_input))
ans_lstm = lstm(dropout(ans_maskedout)) # (A V)
ques_lstm = lstm(dropout(ques_maskedout)) # (Q V)
co_att = Co_AttLayer()([ans_lstm, ques_lstm])
def slice(x, index):
return x[:, :, index, :]
ans_att = Lambda(slice, output_shape=(maxlen, embedd_dim), arguments={'index': 0})(co_att)
ques_att = Lambda(slice, output_shape=(maxlen, embedd_dim), arguments={'index': 1})(co_att)
merged_ques = concatenate([ques_lstm, ques_att, ques_maskedout], axis=2)
merged_ans = concatenate([ans_lstm, ans_att, ans_maskedout], axis=2)
ans_vec = GlobalMaxPooling1D(name='ans_pooling')(merged_ans)
ques_vec = GlobalMaxPooling1D(name='ques_pooling')(merged_ques)
ans_hid = hidden_layer(ans_vec)
ques_hid = hidden_layer(ques_vec)
merged_hid = concatenate([ans_hid, ques_hid], axis=-1)
merged_all = concatenate([merged_hid, ans_hid + ques_hid, ans_hid - ques_hid, K.abs(ans_hid - ques_hid)], axis=-1)
output = output_layer(merged_all)
model = Model(inputs=[ans_input, ques_input], outputs=output)
if init_mean_value:
logger.info("Initialise output layer bias with log(y_mean/1-y_mean)")
bias_value = (np.log(init_mean_value) - np.log(1 - init_mean_value)).astype(K.floatx())
model.layers[-1].b.set_value(bias_value)
if verbose:
model.summary()
start_time = time.time()
model.compile(loss='mse', optimizer='rmsprop')
total_time = time.time() - start_time
logger.info("Model compiled in %.4f s" % total_time)
return model
| 1 | 1 | 0 | 0 | 0 | 0 |
I am creating a TTS system for a native language from which i would create a database of voice recordings from the native people.
I have no experience with Natural Language Processing, and so i would like to know if there are some current tools to achieve my aim?
I am not building from scratch with either laravel or python
Thanks in advance.
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm working on a nlp problem, given a sentence with two entities I need to generate boolean indicating for each word if it stands on the dependency path between those entities.
For example:
'A misty < e1 >ridge< /e1 > uprises from the < e2 >surge< /e2 >'
I want to iterate on each words and tell if it is on the dependency path between e1 and e2
Two important notes:
-If you try to help me (first thanks), don't bother considering the xml markup with < e1 > and < e2 >, I really am interested in how to find if a word is on the dependency path between any two given words with spaCy, I take care of which words by myself
-As I'm not a nlp expert, I'm kind of confused with the meaning of "on the dependency path" and I'm sorry if it is not clear enough (these are the words used by my tutor)
Thanks in advance
| 1 | 1 | 0 | 0 | 0 | 0 |
Below is the code I used to preprocess the text and apply text rank(I followed the gensim textrank tutorial). Please help me with a method to get better results. My text data is a column from a csv with more than 2000 rows. (each row, a sentence).
Output I get is 18 lines (Each different line, not a paragraph) of text as
summary, and 20 words as keywords. Will the output be a paragraph of text as summary? Can we control the number of keywords to be displayed
reg_ex = r'[^a-zA-Z]'
replace = ' '
wordnet_lemmatizer = WordNetLemmatizer()
#stop = stopwords.words('english')
comp_df = df['COMMENT'].str.replace(reg_ex, replace).apply(lambda t: ' '.join([wordnet_lemmatizer.lemmatize(w)for w in t.split()])).str.lower()
aa = comp_df.to_string()
import requests
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
from gensim.summarization import summarize
from gensim.summarization import keywords
print ('Summary:')
print (summarize(aa,ratio=0.01))
print ('
Keywords:')
print (keywords(aa, ratio=0.01))
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm trying to figure out if there is any Python library which allows me to get the percentage value of probability if the string that I'm looking for exists in text or if there is any similar.
To get it more clearly, here is the example:
My string is 'Company Ltd' and in text it exists but under the phrase 'Company Limited'.
The other example, 'Boeing BG' and in text it is present by 'Boeing B.G.'
Is there any way for to get percentage value/probability that it exists in text or not?
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to measure the similarity of company names, however I am having difficulties while I'm trying to match the abbreviations for those names. For example:
IBM
The International Business Machines Corporation
I have tried using fuzzywuzzy to measure the similarity:
>>> fuzz.partial_ratio("IBM","The International Business Machines Corporation")
33
>>> fuzz.partial_ratio("General Electric","GE Company")
20
>>> fuzz.partial_ratio("LTCG Holdings Corp","Long Term Care Group Inc")
39
>>> fuzz.partial_ratio("Young Innovations Inc","YI LLC")
33
Do you know any techniques to measure a higher similarity for such abbreviations?
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm programming a genetic algorithm in Python, however, my operator (MMX) takes too long (10 seconds) to execute for individuals with 3 million weights (each individual is a list of 3.000.000 elements).
This is the code for the operator:
def calc_gen(maxel, minel, rec1, rec2, phiC):
g = maxel - minel
phi = 0
if g > phiC:
# Recta 2
phi = rec2[0] * g + rec2[1]
elif g < phiC:
# Recta 1
phi = rec1[0] * g + rec1[1]
#Hay que asegurarse que no nos salimos del rango:
maxv = min(1, maxel - phi)
minv = max(0, minel + phi)
gen1 = random.uniform(minv, maxv) # Guardar el gen del primer hijo
# Si C es el centro y A el elemento que ya tenemos y B el simétrico de A: C - A + C = B -> 2C - A = B
# C = (maxv + minv) / 2; 2C - A = B -> maxv + minv - A = B
# center = (maxv + minv) / 2
gen2 = maxv + minv - gen1
return gen1, gen2
#return gen1, maxv + minv - gen1
def cxMMX(poblacion, rec1, rec2, phiC):
start = timer()
# Calcular el maximo y el minimo de cada gen en toda la población
max_genes = numpy.amax(poblacion, axis=0).tolist()
min_genes = numpy.amin(poblacion, axis=0).tolist()
gis = timer()
hijo1 = Individual()
hijo2 = Individual()
# Iterar dos listas a la vez (zip) con su indice (enumerate). Así crearemos los hijos simultáneamente en un loop
for i, (maxel, minel) in enumerate(zip(max_genes, min_genes)):
gen1, gen2 = calc_gen(maxel, minel, rec1, rec2, phiC)
hijo1.append(gen1)
hijo2.append(gen2)
end = timer()
#print("Tiempo Gi: %f Tiempo init: %f Tiempo calc gen: %f Tiempo mate total: %f" % (gis-start, init-gis, end-init, end-start))
return [hijo1, hijo2]
rec1, rec2 and phiC are parameters that determine how the crossover is done, you shouldn't bother about them. They have the same value all across the algorithm.
poblacion is a list of lists, lets say it's shape is [7,3000000].
Individual() is a custom class. It is basically inheriting "list" and adding some attributes to store the fitness value.
Doing numpy.amax and numpy.amin separately seems like doing extra work. Also, there's probably a more pythonic way to do the "calc_gen()" loop.
PD: "gen1" depends on "gen2": gen1 obtained randomly within a range, and then gen2 is obtained looking for the symmetrical point.
PD2: A more detailed explanation on MMX operator can be found on the original paper, however, you can assume the code is okay and does what it has to do. The doi is https://doi.org/10.1007/3-540-44522-6_73
PD: the enumerate() and the i are there from the old code, forgot to remove them!
EDIT: reduced 20% time with Dillon Davis's solution. It's a pretty clean solution which will work with any custom list building function, provided you obtain each value of the list by executing one function:
def calc_gen_v2(maxel,minel, rec1m, rec1b, rec2m, rec2b, phiC):
g = maxel - minel
phi = 0
if g > phiC:
# Recta 2
phi = rec2m * g + rec2b
elif g < phiC:
# Recta 1
phi = rec1m * g + rec1b
#Hay que asegurarse que no nos salimos del rango:
maxv = min(1, maxel - phi)
minv = max(0, minel + phi)
gen1 = random.uniform(minv, maxv) # Guardar el gen del primer hijo
# Si C es el centro y A el elemento que ya tenemos y B el simétrico de A: C - A + C = B -> 2C - A = B
# C = (maxv + minv) / 2; 2C - A = B -> maxv + minv - A = B
# center = (maxv + minv) / 2
gen2 = maxv + minv - gen1
return gen1, gen2
def cxMMX_v3(poblacion, rec1, rec2, phiC):
start = timer()
# Calcular el maximo y el minimo de cada gen en toda la población
max_genes = numpy.amax(poblacion, axis=0)
min_genes = numpy.amin(poblacion, axis=0)
gis = timer()
hijo1, hijo2 = map(Individual, numpy.vectorize(calc_gen_v2)(max_genes, min_genes, rec1[0], rec1[1], rec2[0], rec2[1], phiC))
end = timer()
#print("Tiempo Gi: %f Tiempo init: %f Tiempo calc gen: %f Tiempo mate total: %f" % (gis-start, init-gis, end-init, end-start))
return [hijo1, hijo2]
EDIT 2: as Dillon Davis suggested I implemented it in pure numpy, reducing the time to 3,5 seconds! (65% time save)
def cxMMX_numpy(poblacion, rec1, rec2, phiC):
# Calculate max and min for every gen in the population
max_genes = numpy.amax(poblacion, axis=0)
min_genes = numpy.amin(poblacion, axis=0)
g_pop = numpy.subtract(max_genes, min_genes)
phi_pop = numpy.where(g_pop < phiC, numpy.multiply(g_pop, rec1[0]) + rec1[1], numpy.where(g_pop > phiC, numpy.multiply(g_pop, rec2[0]) + rec2[1], 0))
maxv = numpy.minimum(numpy.subtract(max_genes, phi_pop), 1)
minv = numpy.maximum(numpy.sum([min_genes, phi_pop], axis=0), 0)
hijo1 = numpy.random.uniform(low=minv, high=maxv, size=minv.size)
hijo2 = numpy.subtract(numpy.sum([maxv, minv], axis=0), hijo1)
return [Individual(hijo1), Individual(hijo2)]
NOTE: In case you want to reuse, Individual inherits from list
NOTE: if g=phiC then rec1[0] * g_pop + rec1[1]=0, always, rec1[0] and rec1[1] guarantee that! so maybe it is better to do the math instead of a triple option?
| 1 | 1 | 0 | 0 | 0 | 0 |
I'm currently working on a neural network that evaluates students' answers to exam questions. Therefore, preprocessing the corpora for a Word2Vec network is needed. Hyphenation in german texts is quite common. There are mainly two different types of hyphenation:
1) End of line:
The text reaches the end of the line so the last word is sepa-
rated.
2) Short form of enumeration:
in case of two "elements":
Geistes- und Sozialwissenschaften
more "elements":
Wirtschafts-, Geistes- und Sozialwissenschaften
The de-hyphenated form of these enumerations should be:
Geisteswissenschaften und Sozialwissenschaften
Wirtschaftswissenschaften, Geisteswissenschaften und Sozialwissenschaften
I need to remove all hyphenations and put the words back together. I already found several solutions for the first problem.
But I have absoluteley no clue how to get the second part (in the example above "wissenschaften") of the words in the enumeration problem. I don't even know if it is possible at all.
I hope that I have pointet out my problem properly.
So has anyone an idea how to solve this problem?
Thank you very much in advance!
| 1 | 1 | 0 | 0 | 0 | 0 |
I am trying to create custom chunk tags and to extract relations from them. Following is the code that takes me to the cascaded chunk tree.
grammar = r"""
NPH: {<DT|JJ|NN.*>+} # Chunk sequences of DT, JJ, NN
PPH: {<IN><NP>} # Chunk prepositions followed by NP
VPH: {<VB.*><NP|PP|CLAUSE>+$} # Chunk verbs and their arguments
CLAUSE: {<NP><VP>} # Chunk NP, VP
"""
cp = nltk.RegexpParser(grammar)
sentence = [("Mary", "NN"), ("saw", "VBD"), ("the", "DT"), ("cat", "NN"),
("sit", "VB"), ("on", "IN"), ("the", "DT"), ("mat", "NN")]
chunked = cp.parse(sentence)
Output -
(S
(NPH Mary/NN)
saw/VBD
(NPH the/DT cat/NN)
sit/VB
on/IN
(NPH the/DT mat/NN))
Now I am trying to extract relations between the NPH tag values with the text in between using the nltk.sem.extract_rels function, BUT it seems to work ONLY on named entities generated with the ne_chunk function.
IN = re.compile(r'.*\bon\b')
for rel in nltk.sem.extract_rels('NPH', 'NPH', chunked,corpus='ieer',pattern = IN):
print(nltk.sem.rtuple(rel))
This gives the following error -
ValueError: your value for the subject type has not been recognized: NPH
Is there an easy way to use only chunk tags to create relations as I don't really want to retrain the NER model to detect my chunk tags as respective named entities
Thank you!
| 1 | 1 | 0 | 0 | 0 | 0 |
I have a text file which contains some strings that I want to remove from my data frame. The data frame observations contains those texts which are present in the ext file.
here is the text file - https://drive.google.com/open?id=1GApPKvA82tx4CDtlOTqe99zKXS3AHiuD
here is the link; Data = https://drive.google.com/open?id=1HJbWTUMfiBV54EEtgSXTcsQLzQT1rFgz
I am using the following code -
import nltk
from nltk.tokenize import word_tokenize
file = open("D://Users/Shivam/Desktop/rahulB/fliter.txt")
result = file.read()
words = word_tokenize(result)
I loaded the text files and converted them into words/tokens.
Its is my dataframe.
text
0 What Fresh Hell Is This? January 31, 2018 ...A...
1 What Fresh Hell Is This? February 27, 2018 My ...
2 What Fresh Hell Is This? March 31, 2018 Trump ...
3 What Fresh Hell Is This? April 29, 2018 Michel...
4 Join Email List Contribute Join AMERICAblog Ac...
If you see this, these texts are present in the all rows such as "What Fresh Hell Is This?" or "Join Email List Contribute Join AMERICAblog Ac, "Sign in Daily Roundup MS Legislature Elected O" etc.
I used this for loop
for word in words:
df['text'].replace(word, ' ')
my error.
error Traceback (most recent call last)
<ipython-input-168-6e0b8109b76a> in <module>()
----> 1 df['text'] = df['text'].str.replace("|".join(words), " ")
D:\Users\Shivam\Anaconda2\lib\site-packages\pandas\core\strings.pyc in replace(self, pat, repl, n, case, flags)
1577 def replace(self, pat, repl, n=-1, case=None, flags=0):
1578 result = str_replace(self._data, pat, repl, n=n, case=case,
-> 1579 flags=flags)
1580 return self._wrap_result(result)
1581
D:\Users\Shivam\Anaconda2\lib\site-packages\pandas\core\strings.pyc in str_replace(arr, pat, repl, n, case, flags)
422 if use_re:
423 n = n if n >= 0 else 0
--> 424 regex = re.compile(pat, flags=flags)
425 f = lambda x: regex.sub(repl=repl, string=x, count=n)
426 else:
D:\Users\Shivam\Anaconda2\lib\re.pyc in compile(pattern, flags)
192 def compile(pattern, flags=0):
193 "Compile a regular expression pattern, returning a pattern object."
--> 194 return _compile(pattern, flags)
195
196 def purge():
D:\Users\Shivam\Anaconda2\lib\re.pyc in _compile(*key)
249 p = sre_compile.compile(pattern, flags)
250 except error, v:
--> 251 raise error, v # invalid expression
252 if not bypass_cache:
253 if len(_cache) >= _MAXCACHE:
error: nothing to repeat
| 1 | 1 | 0 | 0 | 0 | 0 |
I have recently started using pyBrain to conduct some machine learning research. I am interested in GAs as well as ANNs - however despit the fact that the pyBrain homepage lists GA as one of the features of the library, there does not seem to be anything in the pyBrain documentation on GA programming (e.g. chromosome selection, fitness functions etc), and there are no examples involving GA on the PyBrain site (AFAIK).
Also, equally suprising is that all my searches to find GA examples using PyBrain have also, yielded nothing. Does anyone have a link to code that shows a GA example using pyBrain?
| 1 | 1 | 0 | 1 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.