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 new to document similarity in python and I'm confused about how to go about working with some data. Basically, I want to get the cosine similarity between dicts containing keywords. I have dicts like so, which I am getting straight from a database: {'hat': 0.12, 'cat': 0.33, 'sat': 0.45} {'rat': 0.22, 'bat':0.98, 'cat': 0.01} I query the database and I get back data in this format. These are each lists of keywords and their respective tf-idf scores/weights. {'keyword': tfidf_score} All I want to do is get the cosine similarity between these two dicts, weighted by the tfidf score. Looking online, I was pretty overwhelmed by all the different python libraries/modules when it comes to document similarity. I have no idea if there is some built-in function out there that I can just pass these sorts of json objects to, if I should be writing my own function that uses the weights, or what. Any help is appreciated! Thank you!
1
1
0
0
0
0
First of all I am using Google colab for the work and I have downloaded nltk stopwords for English with following: nltk.download('stopwords') The download was successful [nltk_data] Downloading package stopwords to /root/nltk_data... but when I run stop = stopwords.words('English') I am getting OSError: No such file or directory: '/root/nltk_data/corpora/stopwords/English'
1
1
0
0
0
0
Svenstrup et. al. 2017 propose an interesting way to handle hash collisions in hashing vectorizers: Use 2 different hashing functions, and concatenate their results before modeling. They claim that the combination of multiple hash functions approximates a single hash function with much larger range (see section 4 of the paper). I'd like to try this out with some text data I'm working with in sklearn. The idea would be to run the HashingVectorizer twice, with a different hash function each time, and then concatenate the results as an input to my model. How might I do with with sklearn? There's not an option to change the hash function used, but maybe could modify the vectorizer somehow? Or maybe there's a way I could achieve this with SparseRandomProjection ?
1
1
0
0
0
0
I am using the Gensim Python package to learn a neural language model, and I know that you can provide a training corpus to learn the model. However, there already exist many precomputed word vectors available in text format (e.g. http://www-nlp.stanford.edu/projects/glove/). Is there some way to initialize a Gensim Word2Vec model that just makes use of some precomputed vectors, rather than having to learn the vectors from scratch? Thanks!
1
1
0
0
0
0
I'm trying to remove stop words from strings stored in a pandas DataFrame, but for some reason instead of iterating through the words of the strings I'm iterating through every character, which gives me an unwanted result. I was not able to find any solution to this problem. Can someone please explain why am I iterating through the characters instead of the words in the phrase? I present the code I am using and the results I am getting bellow. The stop words and strings are in Portuguese but I don't think it influences the results. #List of stop words stp = set(stopwords.words('portuguese') + list(punctuation)) print(stp) trainData = pd.DataFrame(columns= ['text', 'response']) corpus = [] with open('pred.txt', 'r') as f_input: corpus += [strip_multiple_whitespaces(line) for line in f_input] corpus_1 = [strip_non_alphanum(line) for line in corpus] corpus_2 = [line.rstrip() for line in corpus_1] train_data = [line.split(' ') for line in corpus_2] for line in train_data: if(line[0] == ''): train_data.remove(line) tmp = pd.DataFrame({'text':train_data[::2], 'response':train_data[1::2]}) trainData = trainData.append(tmp[['text', 'response']], ignore_index=True) trainData['text'] = trainData['text'].astype(str).str.lower() print(trainData) trainData['text'] = trainData['text'].apply(lambda x: [word for word in x if word not in stp]) print(trainData) This is the result of printing the stop words: {'com', 'meu', 'fora', '/', ',', 'aos', 'tu', 'estiver', 'esteve', 'fossem', 'e', 'seu', 'já', '|', 'minha', 'te', 'foi', 'há', 'dos', 'ele', 'fôramos', 'tuas', '[', 'foram', 'para', 'quando', 'for', 'tua', 'estávamos', 'eles', 'sou', 'tiveram', 'estivemos', 'também', 'aquela', 'você', 'tenho', 'às', 'houvera', '-', 'éramos', 'mais', 'houveríamos', '^', '`', '@', 'delas', 'estivéramos', 'nas', 'dele', 'esteja', 'hajamos','hei', 'ela', 'se', ':', 'por', 'na', 'estiverem', 'houveria', 'pelos', 'estivessem', 'tenhamos', 'nos', 'até', 'nós', 'estão', 'tenha', 'teremos', 'nem', 'teu', 'ou', 'estejam', 'fomos', 'sejam', 'forem', 'estive', 'houverei', 'me', '*', 'uma', 'meus', 'houvemos', 'o', 'vocês', 'aquilo', 'não', '%', "'", 'ao', 'minhas', 'tinham', '+', 'do', 'aquele', 'sua', 'hajam', 'sejamos', 'a', 'este', 'num', 'era', 'terá', 'serão', 'tivesse', '=', 'houver', 'esse', 'tiverem', 'um', 'mas', 'nossa', 'está', 'houvéssemos', 'serei', 'houverão', 'estivermos', '?', '~', 'teus', 'fôssemos', 'havemos', 'deles', 'dela', 'tivéssemos', 'tivemos', 'depois', '{', 'nossos', 'nossas', 'estivera', 'seria', ')', 'houvéramos', 'seriam', 'formos', 'estas', 'tinha', 'estejamos', 'tivessem', 'eram', 'será', 'fosse', 'estes', 'teria', 'esta', 'estou', 'pelas', 'houveremos', 'tem', 'houveram', 'estamos', 'lhes', 'estivesse', 'tive', 'numa', 'seja', 'tiver', 'que', '$', 'estavam', '<', 'terei', 'houverá', 'seríamos', '>', 'teríamos', 'pela', 'isto', 'à', 'as', 'esses', ';', 'essas','teve', 'suas', 'de', 'em', 'qual', 'houveriam', '#', 'das', '.', '(', 'hão', 'são', 'mesmo', 'sem', 'vos', 'houve', 'lhe', 'houvermos', 'só', 'houvesse', 'seremos', '\', '}', 'somos', 'como', 'aqueles', 'estiveram', 'temos', 'da', 'tivéramos', 'eu', '"', 'muito', '_', 'nosso', 'pelo', 'no', 'estava', ']', 'tém', 'estivéssemos', 'isso', '&', '!', 'haja', 'tenham', 'elas', 'tivermos', 'terão', 'quem', 'tínhamos', 'teriam', 'os', 'houverem', 'fui', 'tivera', 'aquelas', 'entre', 'seus', 'essa', 'houvessem'} This is my Dataframe before removing the stop words: text response 0 ['o', 'que', 'causa'] [causadorDe] 1 ['o', 'que', 'leva', 'á', 'existência', 'de'] [causadorDe] 2 ['porquê', 'é', 'que', 'existe'] [causadorDe] 3 ['o', 'que', 'é', 'que', 'esta', 'contido', 'no'] [contidoEm] 4 ['o', 'que', 'é', 'que', 'esta', 'contido', 'na'] [contidoEm] 5 ['qual', 'é', 'o', 'antónimo', 'de'] [antonimoNDe] 6 ['qual', 'é', 'o', 'contrário', 'de'] [antonimoNDe] 7 ['o', 'que', 'é', 'o', 'oposto', 'de'] [antonimoNDe] 8 ['qual', 'é', 'a', 'consequência', 'de'] [finalidadeDe] 9 ['qual', 'é', 'o', 'resultado', 'de'] [finalidadeDe] 10 ['o', 'que', 'resulta', 'de'] [finalidadeDe] 11 ['o', 'que', 'usaria', 'para'] [finalidadeDe] 12 ['o', 'que', 'pode', 'ser', 'usado', 'para'] [finalidadeDe] 13 ['qual', 'é', 'a', 'origem', 'de'] [originarioDe] 14 ['de', 'onde', 'vem', 'o'] [originarioDe] 15 ['de', 'onde', 'é', 'derivado', 'o'] [originarioDe] 16 ['qual', 'é', 'a', 'origem', 'de'] [originarioDe] 17 ['de', 'onde', 'vem', 'a'] [originarioDe] 18 ['de', 'onde', 'é', 'derivada', 'a'] [originarioDe] 19 ['para', 'que', 'serve', 'um'] [servePara] 20 ['para', 'que', 'usaria', 'um'] [servePara] 21 ['qual', 'é', 'a', 'finalidade', 'de', 'um'] [servePara] 22 ['para', 'que', 'serve', 'uma'] [servePara] 23 ['para', 'que', 'usaria', 'uma'] [servePara] 24 ['qual', 'é', 'a', 'finalidade', 'de', 'uma'] [servePara] And this is the result after trying to remove those stop words: text response 0 [ , q, u, , c, u, s] [causadorDe] 1 [ , q, u, , l, v, , á, , x, i, s, t, ê, n, ... [causadorDe] 2 [p, r, q, u, ê, , é, , q, u, , x, i, s, t] [causadorDe] 3 [ , q, u, , é, , q, u, , s, t, , c, n, t, ... [contidoEm] 4 [ , q, u, , é, , q, u, , s, t, , c, n, t, ... [contidoEm] 5 [q, u, l, , é, , , n, t, ó, n, i, m, , d] [antonimoNDe] 6 [q, u, l, , é, , , c, n, t, r, á, r, i, , d] [antonimoNDe] 7 [ , q, u, , é, , , p, s, t, , d] [antonimoNDe] 8 [q, u, l, , é, , , c, n, s, q, u, ê, n, c, ... [finalidadeDe] 9 [q, u, l, , é, , , r, s, u, l, t, d, , d] [finalidadeDe] 10 [ , q, u, , r, s, u, l, t, , d] [finalidadeDe] 11 [ , q, u, , u, s, r, i, , p, r] [finalidadeDe] 12 [ , q, u, , p, d, , s, r, , u, s, d, , p, r] [finalidadeDe] 13 [q, u, l, , é, , , r, i, g, m, , d] [originarioDe] 14 [d, , n, d, , v, m, ] [originarioDe] 15 [d, , n, d, , é, , d, r, i, v, d, ] [originarioDe] 16 [q, u, l, , é, , , r, i, g, m, , d] [originarioDe] 17 [d, , n, d, , v, m, ] [originarioDe] 18 [d, , n, d, , é, , d, r, i, v, d, ] [originarioDe] 19 [p, r, , q, u, , s, r, v, , u, m] [servePara] 20 [p, r, , q, u, , u, s, r, i, , u, m] [servePara] 21 [q, u, l, , é, , , f, i, n, l, i, d, d, , ... [servePara] 22 [p, r, , q, u, , s, r, v, , u, m] [servePara] 23 [p, r, , q, u, , u, s, r, i, , u, m] [servePara] 24 [q, u, l, , é, , , f, i, n, l, i, d, d, , ... [servePara]
1
1
0
0
0
0
In a blog post I read that the following "naive implementation" of cosine similarity should never be used in production, the blog post didn't explain why and I am really curious, can anyone give an explanation? import numpy as np def cos_sim(a, b): """Takes 2 vectors a, b and returns the cosine similarity according to the definition of the dot product """ dot_product = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) return dot_product / (norm_a * norm_b) # the counts we computed above sentence_m = np.array([1, 1, 1, 1, 0, 0, 0, 0, 0]) sentence_h = np.array([0, 0, 1, 1, 1, 1, 0, 0, 0]) sentence_w = np.array([0, 0, 0, 1, 0, 0, 1, 1, 1]) # We should expect sentence_m and sentence_h to be more similar print(cos_sim(sentence_m, sentence_h)) # 0.5 print(cos_sim(sentence_m, sentence_w)) # 0.25
1
1
0
0
0
0
Supposedly, Elmo is a word embedding. So if the input is a sentence or a sequence of words, the output should be a sequence of vectors. Apparently, this is not the case. The code below uses keras and tensorflow_hub. a = ['aaa bbbb cccc uuuu vvvv wrwr', 'ddd ee fffff ppppp'] a = np.array(a, dtype=object)[:, np.newaxis] #a.shape==(2,1) input_text = layers.Input(shape=(1,), dtype="string") embedding = ElmoEmbeddingLayer()(input_text) model = Model(inputs=[input_text], outputs=embedding) model.summary() The class ElmoEmbedding is from https://github.com/strongio/keras-elmo/blob/master/Elmo%20Keras.ipynb. b = model.predict(a) #b.shape == (2, 1024) Apparently, the embedding assigns a 1024-dimensional vector to each sentence. This is confusing. Thank you.
1
1
0
0
0
0
I want to create an N-Gram model which will not work with "English words". I have a custom vocabulary list like below: vocabs = [ [0.364, 0.227, 0.376], [0.875, 0.785, 0.376], ........ ] What I am trying to say is, each element in my vocabs list needs to be considered as a "word" by the N-Gram models. And my training dataset will have some numbers exactly in the same format of my vocabs list, like below: training_data = [ [0.344, 0.219, 0.374], [0.846, 0.776, 0.376], ........ ] Note: In the example I wanted to show that, the training "words" (list of 3 number) are not exactly the same as the "words" in my vocabulary but they will be very close. Now, my question is, can I build an N-Gram model which can be trained using the training data? And later, use that model to predict the probability of a new "word" as it comes. I am using python and can find a lot of N-Gram examples using the "nltk" library. But the problem is in most cases "English words" are used. As I am not very familiar with N-Grams, these examples made me confused. I will be very happy if anyone can answer my questions and/or point out some tutorials to learn N-Grams in general (not specific to NLP). Thanks. Edit: Just to simplify the question, I will try to explain it in a different way: I have a vocabulary like below: vocabs = [v1, v2, v3, ........vn] I also have two sequence generator(SG). Both of them generates a sequence of words from my vocabulary. My goal is to predict from the streaming data: which generator is currently generating the sequence(words). Now I want to build two N-gram models(one for each SG) using my labeled training data(I already have some labeled data from the SGs). Finally, when I feed my streaming data into the models and select the probable SG by comparing predictions from the N-gram models. Just to be clear if the N-gram model for SG1 gives higher probability than the N-gram model for SG2, I will decide that the current streaming data is generated by SG1. Hope the explanation helps to understand my concern. I really appreciate the effort to answer this question. Note: If you know any other models that can solve this problem well (better than N-gram model), please mention them. Thanks.
1
1
0
0
0
0
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits para = "support leaders around the world who do not speak for the big polluters, but who speak for all of humanity, for the indigenous people of the world, for the first 100 people.In 90's it seems true." import re import nltk sentences = nltk.sent_tokenize(para) for i in range(len(sentences)): words = nltk.word_tokenize(sentences[i]) words = [re.sub(r'\d','',words)] sentences[i] = ' '.join(words) while doing this i am getting following error: TypeError Traceback (most recent call last) <ipython-input-28-000671b45ee1> in <module>() 2 for i in range(len(sentences)): 3 words = nltk.word_tokenize(sentences[i]) ----> 4 words = [re.sub(r'\d','',words)].encode('utf8') 5 sentences[i] = ' '.join(words) ~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags) 189 a callable, it's passed the match object and must return 190 a replacement string to be used.""" --> 191 return _compile(pattern, flags).sub(repl, string, count) 192 193 def subn(pattern, repl, string, count=0, flags=0): TypeError: expected string or bytes-like object How can i convert to byte like object. I am confused as i am new to it.
1
1
0
0
0
0
In order to extract the "PERSON" labels of some sentences, I'm training spacy with some sentences like "John Doe likes London and Berlin". For this example, the training data would look like this : TRAIN_DATA = [ ('John Doe likes London and Berlin.', { 'entities': [(0, 8, 'PERSON'), (15, 21, 'LOC'), (26, 32, 'LOC')] })] But I don't want to specify the other labels like London = LOC and Berlin = Loc like I did in this example. Is it possible or do I always have to specify the other labels ?
1
1
0
0
0
0
I got a problem in torchtext, and was struggling with it for a long time. I was trying to tokenize and numericalize the text using torchtext and spacy. I defined my tokenizer as this: def Sp_Tokenizer(text): return [tok.text for tok in spacy_en.tokenizer(text)] It worked good: Sp_Tokenizer('How are you today') ['How', 'are', 'you', 'today'] Then I passed this tokenizer into torchtext: TEXT = data.Field(sequential=True, tokenize=Sp_Tokenizer, lower=False) and built the vocab: corps = ['How are you', 'I am good today', 'He is not well'] TEXT.build_vocab(corps, vectors="glove.6B.100d") Then I tried TEXT.numericalize('How are you today') I assumed I should get a tensor with 4 numbers (word level), however, what I got was like char level: tensor([[ 6, 3, 10, 2, 4, 17, 5, 2, 11, 3, 19, 2, 9, 3, 7, 4, 11]]) What's wrong with that? Is there anythin I can do to fix it? Thanks!
1
1
0
0
0
0
I want to use char sequences and word sequences as inputs. Each of them will be embedded its related vocabulary and then resulted embeddings will be concatenated. I write following code to concatenate two embeddings: char_model = Sequential() char_model.add(Embedding(vocab_size, char_emnedding_dim,input_length=char_size,embeddings_initializer='random_uniform',trainable=False, input_shape=(char_size, ))) word_model = Sequential() word_model.add(Embedding(word_vocab_size,word_embedding_dim, weights=[embedding_matrix], input_length=max_length, trainable=False,input_shape=(max_length, ))) model = Sequential() model.add(Concatenate([char_model, word_model])) model.add(Dropout(drop_prob)) model.add(Conv1D(filters=250, kernel_size=3, padding='valid', activation='relu', strides = 1)) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) # fully connected layer model.add(Dropout(drop_prob)) model.add(Activation('relu')) model.add(Dense(num_classes)) model.add(Activation('softmax')) print(model.summary()) When I execute the code, I have the following error: ValueError: This model has not yet been built. Build the model first by calling build() or calling fit() with some data. Or specify input_shape or batch_input_shape in the first layer for automatic build. I defined input_shape for each embedding, but I still have same error. How can I concatenate two sequential model?
1
1
0
1
0
0
I am trying to run a Python code that counts the frequency of certain pre-defined keywords in a text. However, I only get zeros when running the script posted below (i.e. the script does not count any occurence of a keyword in the targeted text). It seems that the error is stuck in the line "X = vectorizer.fit_transform(text)" since it always returns an empty variable X. What I am trying to get as a result in this short example is a table that lists the counts of each flavour of icecream in a separate column, followed by the sum of individual counts. import pandas as pd from collections import Counter from sklearn.feature_extraction.text import CountVectorizer icecream = ['Vanilla', 'Strawberry', 'Chocolate', 'Peach'] vectorizer = CountVectorizer(vocabulary=icecream, encoding='utf8', lowercase=True, analyzer='word', decode_error='ignore', ngram_range=(1, 1)) dq = pd.DataFrame(columns=icecream) vendor = 'Franks Store' text = ['We offer Vanilla with Hazelnut, Vanilla with Coconut, Chocolate and Strawberry'] X = vectorizer.fit_transform(text) vocab = vectorizer.get_feature_names() counts = X.sum(axis=0).A1 freq_distribution = Counter(dict(zip(vocab, counts))) allwords = dict(freq_distribution) totalnum = sum(allwords.values()) allwords.update({'totalnum': totalnum}) dy = pd.DataFrame.from_dict(allwords, orient='index') dy.columns = [vendor] dy = dy.transpose() dq = dy.append(dq, sort=False) print(dq) If you have an idea on what might be wrong with this code, I would be very happy if you share it with me. Thank you!
1
1
0
1
0
0
What is the correct way to use gensim's Phrases and preprocess_string together ?, i am doing this way but it a little contrived. from gensim.models.phrases import Phrases from gensim.parsing.preprocessing import preprocess_string from gensim.parsing.preprocessing import strip_tags from gensim.parsing.preprocessing import strip_short from gensim.parsing.preprocessing import strip_multiple_whitespaces from gensim.parsing.preprocessing import stem_text from gensim.parsing.preprocessing import remove_stopwords from gensim.parsing.preprocessing import strip_numeric import re from gensim import utils # removed "_" from regular expression punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^`{|}~""" RE_PUNCT = re.compile(r'([%s])+' % re.escape(punctuation), re.UNICODE) def strip_punctuation(s): """Replace punctuation characters with spaces in `s` using :const:`~gensim.parsing.preprocessing.RE_PUNCT`. Parameters ---------- s : str Returns ------- str Unicode string without punctuation characters. Examples -------- >>> from gensim.parsing.preprocessing import strip_punctuation >>> strip_punctuation("A semicolon is a stronger break than a comma, but not as much as a full stop!") u'A semicolon is a stronger break than a comma but not as much as a full stop ' """ s = utils.to_unicode(s) return RE_PUNCT.sub(" ", s) my_filter = [ lambda x: x.lower(), strip_tags, strip_punctuation, strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short, stem_text ] documents = ["the mayor of new york was there", "machine learning can be useful sometimes","new york mayor was present"] sentence_stream = [doc.split(" ") for doc in documents] bigram = Phrases(sentence_stream, min_count=1, threshold=2) sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] test = " ".join(bigram[sent]) print(preprocess_string(test)) print(preprocess_string(test, filters=my_filter)) The result is: ['mayor', 'new', 'york'] ['mayor', 'new_york'] #correct part of the code was taken from: How to extract phrases from corpus using gensim
1
1
0
0
0
0
I have the following df, containing daily articles from different sources: print(df) Date content 2018-11-01 Apple Inc. AAPL 1.54% reported its fourth cons... 2018-11-01 U.S. stocks climbed Thursday, Apple is a real ... 2018-11-02 GONE are the days when smartphone manufacturer... 2018-11-03 To historians of technology, the story of the ... 2018-11-03 Apple Inc. AAPL 1.54% reported its fourth cons... 2018-11-03 Apple is turning to traditional broadcasting t... (...) I would like to compute the total number of daily mentions - hence aggregating by Date - of the word "Apple". How can I create "final_df"? print(final_df) 2018-11-01 2 2018-11-02 0 2018-11-03 2 (...)
1
1
0
0
0
0
so I'm sure everyone has heard about the Berkeley Pac-Man AI challenge at some point or another. A while ago I created a 2D platformer (doesn't scroll) and figured it would be pretty cool to take some inspiration from this project but create an AI for my game (instead of PacMan). That being said, I have found myself very stuck. I have looked at several GitHub solutions for the PacMan as well as plenty of articles regarding implementation of MDP / Reinforced learning in Python. I'm having a hard time relating them back to my game. In my game, I have 10 levels. Each level has fruit, and once the agent grabs all the fruit, he completes the level and the next level starts. Here's an example stage: As you can see in this picture, my agent is the little squirrel and he has to grab all the cherries. On the ground there's also spikes that he can't walk on (or you lose a life). You can avoid spikes by jumping. So a jump technically moves the agent 2 spaces to the left or right (depending on way he's facing). Other than that you can move left, right, up and down on a ladder. You can't jump more than 1 space, so the "2+ gappers" at the top you see, you'd have to climb down the ladder and go around. Additionally, not pictured above there are enemies that go Left and Right only on a floor that you have to dodge (you can jump over them, or just avoid them). They're tracked on a grid I'll talk about below. So that's a bit about the game, if you need anymore clarifications, feel free to ask and I can assist, let me go into what I've tried now a little bit and see if someone can assist me with getting something together. In my code I have a grid that has all the spaces on the map and what they are (platform, regular spot, spike, reward/fruit, ladder, etc). Using that, I created an action grid (code below) that basically stores in a dictionary all of the spots the agent can move from each location. for r in range(len(state_grid)): for c in range(len(state_grid[r])): if(r == 9 or r == 6 or r == 3 or r == 0): if (move_grid[r][c] != 6): actions.update({state_grid[r][c] : 'None'}) else: actions.update({state_grid[r][c] : [('Down', 'Up')]}) elif move_grid[r][c] == 4 or move_grid[r][c] == 0 or move_grid[r][c] == 2 or move_grid[r][c] == 3 or move_grid[r][c] == 5: actions.update({state_grid[r][c] : 'None'}) elif move_grid[r][c] == 6: if move_grid[r+1][c] == 4 or move_grid[r+1][c] == 2 or move_grid[r+1][c] == 3 or move_grid[r+1][c] == 5: if c > 0 and c < 18: actions.update({state_grid[r][c] : [('Left', 'Right', 'Up', 'Jump Left', 'Jump Right')]}) elif c == 0: actions.update({state_grid[r][c] : [('Right', 'Up', 'Jump Right')]}) elif c == 18: actions.update({state_grid[r][c] : [('Left', 'Up', 'Jump Left')]}) elif move_grid[r+1][c] == 6: actions.update({state_grid[r][c] : [('Down', 'Up')]}) elif move_grid[r][c] == 1 or move_grid[r][c] == 8 or move_grid[r][c] == 9 or move_grid[r][c] == 10: if c > 0 and c < 18: if move_grid[r+1][c] == 6: actions.update({state_grid[r][c] : [('Down', 'Left', 'Right', 'Jump Left', 'Jump Right')]}) else: actions.update({state_grid[r][c] : [('Left', 'Right', 'Jump Left', 'Jump Right')]}) elif c == 0: if move_grid[r+1][c] == 6: actions.update({state_grid[r][c] : [('Down', 'Right', 'Jump Right')]}) else: actions.update({state_grid[r][c] : [('Right', 'Jump Right')]}) elif c == 18: if move_grid[r+1][c] == 6: actions.update({state_grid[r][c] : [('Down', 'Left', 'Jump Left')]}) else: actions.update({state_grid[r][c] : [('Left', 'Jump Left')]}) elif move_grid[r][c] == 7: actions.update({state_grid[r][c] : 'Spike'}) else: actions.update({state_grid[r][c] : 'WTF'}) At this point I'm kind of just stuck on how/what is needed to send to the MDP. I'm using the Berkeley MDP and I'm just super stuck on how to start getting it involved and implemented. I have a bunch of the data points and where stuff is, just not sure how to actually get the ball rolling. I have a boolean grid that tracks all the harmful objects (spikes and enemies) and is updated constantly since the enemies move every second. I created a reward grid that sets: Spikes "-5" reward Falling off the map "-5" reward Fruit is a "5" reward Everything else is a "-0.2" reward (since you want to optimize steps, not trying to be on level 1 all day). Another part of my issue during researching solutions or ways to implement this is that most of the solutions are cars driving to a position. So they only have 1 reward position whereas mine has multiple fruits per stage. Yeah I'm just super stuck and getting frustrated with this. Wanted to try my own thing but if I can't do this I might as well just do the Pac-Man one since there's several online solutions. I appreciate your time and help with this! Edit: So here's me trying to make an example call get the move grid back, although from my understanding (and obviously) it will dynamically change after each step the agent makes since the enemy will threaten certain spots and all. This is the result, you can see like it's close but obviously a little stuck up on the fact that there's multiple rewards. I feel like I might be close, but I'm not really sure. I'm a little frustrated at this point.
1
1
0
0
0
0
I have a table with both numeric and string data but in separate columns. The table is answers to a web form and contains empty cells. I want to use text processing on the string columns. I cannot drop the rows with empty cells so for the empty string columns, I replaced the NaN with aplhabet 'a'. Sample data colmun_name1 column_name2 column_name3 column_name4 classify This is a cat This is a dog 1 2 0 This is a rat This is a mouse 45 32 1 a Good mouse 0 0 0 I used the following code to make sure all data in the string columns is actually string data. df2=df[[column_name1, column_name2]] for i in range(0,len(df2)): cell=df2.iloc[i] cell=str(str) df2.iloc[i]=cell Then when I tokenize, I get an error <ipython-input-64-24a99733ba19> in <module> 1 from nltk.tokenize import word_tokenize ----> 2 tokenized_word=word_tokenize(df2) 3 print(tokenized_word) /anaconda3/lib/python3.6/site-packages/nltk/tokenize/__init__.py in word_tokenize(text, language, preserve_line) 126 :type preserver_line: bool 127 """ --> 128 sentences = [text] if preserve_line else sent_tokenize(text, language) 129 return [token for sent in sentences 130 for token in _treebank_word_tokenizer.tokenize(sent)] /anaconda3/lib/python3.6/site-packages/nltk/tokenize/__init__.py in sent_tokenize(text, language) 93 """ 94 tokenizer = load('tokenizers/punkt/{0}.pickle'.format(language)) ---> 95 return tokenizer.tokenize(text) 96 97 # Standard word tokenizer. /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in tokenize(self, text, realign_boundaries) 1239 Given a text, returns a list of the sentences in that text. 1240 """ -> 1241 return list(self.sentences_from_text(text, realign_boundaries)) 1242 1243 def debug_decisions(self, text): /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in sentences_from_text(self, text, realign_boundaries) 1289 follows the period. 1290 """ -> 1291 return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] 1292 1293 def _slices_from_text(self, text): /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in <listcomp>(.0) 1289 follows the period. 1290 """ -> 1291 return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] 1292 1293 def _slices_from_text(self, text): /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in span_tokenize(self, text, realign_boundaries) 1279 if realign_boundaries: 1280 slices = self._realign_boundaries(text, slices) -> 1281 for sl in slices: 1282 yield (sl.start, sl.stop) 1283 /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _realign_boundaries(self, text, slices) 1320 """ 1321 realign = 0 -> 1322 for sl1, sl2 in _pair_iter(slices): 1323 sl1 = slice(sl1.start + realign, sl1.stop) 1324 if not sl2: /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _pair_iter(it) 311 """ 312 it = iter(it) --> 313 prev = next(it) 314 for el in it: 315 yield (prev, el) /anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _slices_from_text(self, text) 1293 def _slices_from_text(self, text): 1294 last_break = 0 -> 1295 for match in self._lang_vars.period_context_re().finditer(text): 1296 context = match.group() + match.group('after_tok') 1297 if self.text_contains_sentbreak(context): TypeError: expected string or bytes-like object I tried changing df2=df[column_name1][column_name2] But I get the same error. What should I do?
1
1
0
1
0
0
Suppose I have the following customer review and I want to know the sentiment about the hotel and the food: "The room we got was nice but the food was average" So had this been in a dataframe of reviews, the output from the analysis would have looked like: Reviews Hotel Food The room was ... Pos Neg I have come across multiple tutorials on Kaggle and Medium which teach sentiment analysis, but they always look for the overall sentiment. Please help me out, if you know the way, or are aware of any tutorials or know what terms to google to get around this problem. Thanks! Edit: Please refer to these sides: http://sentic.net/sentire2011ott.pdf They seem to be lecture notes. Does anyone know a python implementation of the same? Thanks! Edit: This question pertains to ABSA (Aspect Based Sentiment Analysis)
1
1
0
0
0
0
I would like to use Named Entity Recognition (NER) to auto summarize Airline ticket based on a given dataset. So basically this is my dataset. Here i need to create a summary about the details of passenger in a pdf like : The PNR Number ____(PNRNum) refers to the passenger name ____(Name) travelling from ____(Dep Airport),____(Start Country) to ____(Arr Airport),____(End Country) starting at ____(Start Time). The flight number is ____(Flight No) which is _____(Int Dom) using _____(Cabin Class) ticket of base fare _____(Base Fare). Here when the PNR Number should be given as input to enter in the first blank space and the corresponding data from dataset should be filled in remaining blank spaces. airline = pd.read_csv("AIR-LINE.csv") def create_airline_ticket(): c = canvas.Canvas('AIRlines.pdf') c.setFont("Courier", 20) c.drawCentredString(300, 700, 'Airline Ticket') c.setFont("Courier", 14) form = c.acroForm c.drawString(10, 650, 'The PNR Number') options = [('airline.loc[[0, 10], :]')] form.choice(name='choice1', tooltip='Field choice1', value='A', x=165, y=645, width=72, height=20, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True, options=options) c.save() I thought of using ReportLabs module in order to use listbox available in it. But it didn't go accordingly. I have to do with some other way. So could you suggest me a step by step procedure? Since i'm a beginner in python, i could learn easily. Thanks.
1
1
0
0
0
0
def scorer(self, searcher, fieldname, text, qf=1): """Returns an instance of :class:`whoosh.scoring.Scorer` configured for the given searcher, fieldname, and term text. """ raise NotImplementedError(self.__class__.__name__) i do not know the arguments in scorer function.Where are they coming from?and the same to the function under this sentence.If i want to get the term frequences in all collections,not the weight in current doc.How can i do? def _score(self, weight, length): # Override this method with the actual scoring function raise NotImplementedError(self.__class__.__name__)
1
1
0
0
0
0
I have two dataframes with a common key-product names, what i want to do is create a third dataframe by joining the previous two based on partial string matches with 80-90% similarity, the datasets are quite large, i had tried using tfidf from scikit-learn, but i keep losing my reference index. In below example:Mini Wireless Bluetooth Sports Stereo Headset and OnePlus 6 Sandstone Protective Case both need to come in df3, Help will be much appreciated. Output1 Example- import pandas as pd df1=pd.DataFrame({'Product_Name1': ['Mini Wireless Bluetooth Sports Stereo Headset', 'VR Box 3D Smart Glass With Remote Controller', 'OnePlus 6 Sandstone Protective Case'],'Price1': [40000, 50000, 42000]}) df2=pd.DataFrame({'Product_Name2': ['Mini Wireless Sports Stereo Headset', 'VR Box 3D Smart Glass With Remote Controller', 'OnePlus 6 1Sandstone Protective Case'], 'Price2': [40000, 50000, 42000]}) df1set=df1.set_index('Product_Name1') df2set=df2.set_index('Product_Name2') df3=df1set.join(df2set,how='inner') df3 df1 df2 First dataframe Second dataframe
1
1
0
0
0
0
I am looking to use spaCy for my research and morphological information is important for me. Reading the documentation on rule-based morphology, I can't figure out how I can convert the tag (e.g. NNP, VBZ) to morphological vectors (e.g. VerbForm=Fin, Mood=Ind, Tense=Pres). Is there perhaps a built-in tag map available? Something like this (built-in) would be useful, but I can't seem to find it: { "NNS": {POS: NOUN, "Number": "plur"}, "VBG": {POS: VERB, "VerbForm": "part", "Tense": "pres", "Aspect": "prog"}, "DT": {POS: DET} ... } I found the PoS Tagging table, but I can't find out if this mapping is available in code or even directly in the parsed tokens? I found the tagmap for English on GitHub but I'm unsure how to import it. Any help?
1
1
0
0
0
0
Layer (type) Output Shape Param # ================================================================= input_13 (InputLayer) (None, 5511, 101) 0 _________________________________________________________________ conv1d_13 (Conv1D) (None, 1375, 196) 297136 _________________________________________________________________ batch_normalization_27 (Batc (None, 1375, 196) 784 _________________________________________________________________ activation_13 (Activation) (None, 1375, 196) 0 _________________________________________________________________ dropout_34 (Dropout) (None, 1375, 196) 0 _________________________________________________________________ gru_18 (GRU) (None, 1375, 128) 124800 _________________________________________________________________ dropout_35 (Dropout) (None, 1375, 128) 0 _________________________________________________________________ batch_normalization_28 (Batc (None, 1375, 128) 512 _________________________________________________________________ gru_19 (GRU) (None, 1375, 128) 98688 _________________________________________________________________ dropout_36 (Dropout) (None, 1375, 128) 0 _________________________________________________________________ batch_normalization_29 (Batc (None, 1375, 128) 512 _________________________________________________________________ dropout_37 (Dropout) (None, 1375, 128) 0 _________________________________________________________________ time_distributed_11 (TimeDis (None, 1375, 1) 129 ================================================================= Total params: 522,561 Trainable params: 521,657 Non-trainable params: 904 ValueError: Error when checking target: expected time_distributed_3 to have shape (1375, 1) but got array with shape (5511, 101) i'm giving .npy file as input to the cnn layer. array is of size (5, 5511, 101) is it problem with the input array ? how to overcome that value error . i'm using keras (jupyter notebook).I am unable to find any solution .any help would be appreciated. code snippet @ErselEr...this is the code i'm using to build the model def model(input_shape): X_input = Input(shape = input_shape) y = Input(shape = input_shape) ### START CODE HERE ### # Step 1: CONV layer (≈4 lines) X = Conv1D(196, kernel_size=15, strides=4)(X_input) X = BatchNormalization()(X) # Batch normalization X = Activation('relu')(X) # ReLu activation X = X = Dropout(0.8)(X) # dropout (use 0.8) # Step 2: First GRU Layer (≈4 lines) X = GRU(units = 128, return_sequences = True)(X) # GRU (use 128 units and return the sequences) X = Dropout(0.8)(X) # dropout (use 0.8) X = BatchNormalization()(X) # Batch normalization # Step 3: Second GRU Layer (≈4 lines) X = GRU(units = 128, return_sequences = True)(X) # GRU (use 128 units and return the sequences) X = Dropout(0.8)(X) # dropout (use 0.8) X = BatchNormalization()(X) # Batch normalization # dropout (use 0.8) # Step 4: Time-distributed dense layer (≈1 line) X = TimeDistributed(Dense(1,activation = "sigmoid"))(X) # time distributed (sigmoid) ### END CODE HERE ### model = Model(inputs=X_input, outputs=X) return model
1
1
0
0
0
0
I'm currently approaching a classification problem with the following situation: The labels are always 5 digits long, e.g.: 99923 this is sample document one 56743 this is sample document two ... where the first single digit stands for a certain category, every following digit for a subcategory and so on. Currently I'm using Keras with the following settings: model = Sequential() model.add(Dense(512, input_shape=(vocab_size,))) model.add(Activation('relu')) model.add(Dropout(0.3)) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.3)) model.add(Dense(num_labels)) model.add(Activation('softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) Because my training data is limited (around 80k samples overall), I decided to use only the first digit to estimate the main-category and I got pretty good results with ~90% accuracy without any preprocessing which yet has to be done. 5 - this is sample of maincategory 5 9 - this is sample of maincategory 9 ... Now I wanted to approach a level further and use two digits to predict the main-category and the first subcategory. That brought me to the problem that there is often not a single sample for e.g. the combination "12". 51 - this is sample of maincategory 51 95 - this is sample of maincategory 95 ... I told Keras to only use the labels with at least 1 sample (knowing that this is crap) and got around 40 labels with an overall accuracy of 85% which seems to be pretty good given the fact that I've lost many samples. My question is: Can this kind of prediction be done more easily/efficiently? If I let my "two-digits" model predict an unseen sample out of a category which hasn't been trained, I would run into the problem of fitting a sample into a wrong category... Can I solve this prediction problem using Keras?
1
1
0
1
0
0
I know it is possible to find bigrams which have a particular word from the example in the link below: finder = BigramCollocationFinder.from_words(text.split()) word_filter = lambda w1, w2: "man" not in (w1, w2) finder.apply_ngram_filter(word_filter) bigram_measures = nltk.collocations.BigramAssocMeasures() raw_freq_ranking = finder.nbest(bigram_measures.raw_freq, 10) #top-10 >>> nltk: how to get bigrams containing a specific word But I am not sure how this can be applied if I need bigrams containing both words pre-defined. Example: My Sentence: "hello, yesterday I have seen a man walking. On the other side there was another man yelling: "who are you, man?" Given a list:["yesterday", "other", "I", "side"] How can I get a list of bi-grams with the given words. i.e: [("yesterday", "I"), ("other", "side")]?
1
1
0
0
0
0
Currently, i have a dataframe contain words and weight (tf*idf) and i wanna show words which are arranged following weight in wordcloud. Dataframe is on the left image. def generate_wordcloud(words_tem): word_cloud = WordCloud(width = 512, height = 512, background_color='white', stopwords= None, max_words=20).generate(words_tem) plt.figure(figsize=(10,8),facecolor = 'white', edgecolor='blue') plt.imshow(word_cloud, interpolation='bilinear') plt.axis('off') plt.tight_layout(pad=0) plt.show() tfidf = TfidfVectorizer(data, lowercase = False) tfs = tfidf.fit_transform([data]) feature_names = tfidf.get_feature_names() df = pd.DataFrame(tfs.T.toarray(), index=feature_names, columns= ['weight']) df = df.sort_values(by = 'weight', ascending = False) word_lists = df.index.values unique_str = ' '.join(word_lists) print(df[0:20]) generate_wordcloud(unique_str)
1
1
0
0
0
0
I'm trying to create a data prediction model through artificial neural networks. The following code is part of the Python-based ANN code created through many books. Also, the error rate between the predicted value and the actual value doesn't meet below 19%. I tried to increase the number of hidden layers, but it did not tremendously affect the error rate. I think this is probably a limitation of Sigmoid function and not considering Bias. I looked around for a month and found out how to build ReLU and Bias, but I could not find the range of Bias and ReLU. Q1 = How do I convert Sigmoid to ReLU and Q2 = how to add Bias to my code? Q3 = Also, If I change Sigmoid to ReLU, do I have to make my dataset 0.0~1.0 range? This is because Sigmoid function accepts 0.0~1.0 range of data, but I don't know what range ReLU allows. I'm sorry to ask an elementary question. class neuralNetwork: # initialize the neural network def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # self.inodes = input_nodes self.hnodes = hidden_nodes self.onodes = output_nodes # link weight matrices, wih and who self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes)) self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)) # learning rate self.lr = learning_rate # activation function is the sigmoid function self.activation_function = lambda x: scipy.special.expit(x) pass # train the neural network def train(self, inputs_list, targets_list): # convert inputs list to 2d array inputs = numpy.array(inputs_list, ndmin=2).T targets = numpy.array(targets_list, ndmin=2).T # calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) # calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs) # calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) # calculate the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) # output layer error is the (target - actual) output_errors = targets - final_outputs # hidden layer error is the output_errors, split by weights, recombined at hidden nodes hidden_errors = numpy.dot(self.who.T, output_errors) # update the weights for the links between the hidden and output layers self.who += self.lr*numpy.dot((output_errors*final_outputs*(1.0-final_outputs)), numpy.transpose(hidden_outputs)) # update the weights for the links between the input and output layers self.wih += self.lr*numpy.dot((hidden_errors*hidden_outputs*(1.0-hidden_outputs)), numpy.transpose(inputs)) pass # query the neural network def query(self, inputs_list) : inputs = numpy.array(inputs_list, ndmin=2).T # convert hidden list to 2d array hidden_inputs = numpy.dot(self.wih, inputs) # calculate signals into hidden layer hidden_outputs = self.activation_function(hidden_inputs) final_inputs = numpy.dot(self.who, hidden_outputs) final_outputs = self.activation_function(final_inputs) return final_outputs pass
1
1
0
0
0
0
How to convert pretrained fastText vectors to gensim model? I need predict_output_word method. import gensim from gensim.models import Word2Vec from gensim.models.wrappers import FastText model_wiki = gensim.models.KeyedVectors.load_word2vec_format("wiki.ru.vec") model3 = Word2Vec(sentences=model_wiki) TypeError Traceback (most recent call last) in ----> 1 model3 = Word2Vec(sentences=model_wiki) # train a model from the corpus ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/word2vec.py in init(self, sentences, corpus_file, size, alpha, window, min_count, max_vocab_size, sample, seed, workers, min_alpha, sg, hs, negative, ns_exponent, cbow_mean, hashfxn, iter, null_word, trim_rule, sorted_vocab, batch_words, compute_loss, callbacks, max_final_vocab) 765 callbacks=callbacks, batch_words=batch_words, trim_rule=trim_rule, sg=sg, alpha=alpha, window=window, 766 seed=seed, hs=hs, negative=negative, cbow_mean=cbow_mean, min_alpha=min_alpha, compute_loss=compute_loss, --> 767 fast_version=FAST_VERSION) 768 769 def _do_train_epoch(self, corpus_file, thread_id, offset, cython_vocab, thread_private_mem, cur_epoch, ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/base_any2vec.py in init(self, sentences, corpus_file, workers, vector_size, epochs, callbacks, batch_words, trim_rule, sg, alpha, window, seed, hs, negative, ns_exponent, cbow_mean, min_alpha, compute_loss, fast_version, **kwargs) 757 raise TypeError("You can't pass a generator as the sentences argument. Try an iterator.") 758 --> 759 self.build_vocab(sentences=sentences, corpus_file=corpus_file, trim_rule=trim_rule) 760 self.train( 761 sentences=sentences, corpus_file=corpus_file, total_examples=self.corpus_count, ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/base_any2vec.py in build_vocab(self, sentences, corpus_file, update, progress_per, keep_raw_vocab, trim_rule, **kwargs) 934 """ 935 total_words, corpus_count = self.vocabulary.scan_vocab( --> 936 sentences=sentences, corpus_file=corpus_file, progress_per=progress_per, trim_rule=trim_rule) 937 self.corpus_count = corpus_count 938 self.corpus_total_words = total_words ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/word2vec.py in scan_vocab(self, sentences, corpus_file, progress_per, workers, trim_rule) 1569 sentences = LineSentence(corpus_file) 1570 -> 1571 total_words, corpus_count = self._scan_vocab(sentences, progress_per, trim_rule) 1572 1573 logger.info( ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/word2vec.py in _scan_vocab(self, sentences, progress_per, trim_rule) 1538 vocab = defaultdict(int) 1539 checked_string_types = 0 -> 1540 for sentence_no, sentence in enumerate(sentences): 1541 if not checked_string_types: 1542 if isinstance(sentence, string_types): ~/anaconda3/envs/pym/lib/python3.6/site-packages/gensim/models/keyedvectors.py in getitem(self, entities) 337 return self.get_vector(entities) 338 --> 339 return vstack([self.get_vector(entity) for entity in entities]) 340 341 def contains(self, entity): TypeError: 'int' object is not iterable
1
1
0
0
0
0
I am trying to cluster sentences based on their similarity to each other. I am generating the embedding of the sentence using ELMo (where it generates embedding for each word and I sum all of those and divide it by the no. of words). I initially tried to fit this data with tsne, with the embeddings generated by ELMo (512 dimensions) I was able to form clusters, but the problem here is, in tsne the dimensions has to be reduced where it can accommodate maximum of 3 dimensions. Hence the output was not that accurate. Then I tried with DBSCAN, where I don't see any constrain with the dimension of the input fed to it (Please correct me if I am wrong). Now I am struck with plotting the predictions that is been done with DBSCAN. Also when I tried printing the labels predicted, all of them was '-1'. Is there any other way I can cluster the sentences or how can I efficiently utilise the 512 dimension embedding in clustering the sentence with either tsne or dbscan? def tsnescatterplot(sentences): arr = np.empty((0, 512), dtype='f') word_labels = [] for sentence in sentences: wrd_vector = get_elmo_embeddings(sentence) print(sentence) word_labels.append(sentence) arr = np.append(arr, np.array([wrd_vector]), axis=0) print('Printing array') print(arr) # find tsne coords for 2 dimensions tsne = TSNE(n_components=2, random_state=0) np.set_printoptions(suppress=True) Y = tsne.fit_transform(arr) x_coords = Y[:, 0] y_coords = Y[:, 1] # display scatter plot plt.scatter(x_coords, y_coords) for label, x, y in zip(word_labels, x_coords, y_coords): plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords='offset points') plt.xlim(x_coords.min() + 0.5, x_coords.max() + 0.5) plt.ylim(y_coords.min() + 0.5, y_coords.max() + 0.5) plt.show() def dbscan_scatterplot(sentences): arr = np.empty((0, 512), dtype='f') for sentence in sentences: wrd_vector = get_elmo_embeddings(sentence) arr = np.append(arr, np.array([wrd_vector]), axis=0) dbscan = DBSCAN() np.set_printoptions(suppress=True) Y = dbscan.fit(arr)
1
1
0
1
0
0
I lemmatised several sentences, and it turns out the results like this,this is for the first two sentences. ['She', 'be', 'start', 'on', 'Levofloxacin', 'but', 'the', 'patient', 'become', 'hypotensive', 'at', 'that', 'point', 'with', 'blood', 'pressure', 'of', '70/45', 'and', 'receive', 'a', 'normal', 'saline', 'bolus', 'to', 'boost', 'her', 'blood', 'pressure', 'to', '99/60', ';', 'however', 'the', 'patient', 'be', 'admit', 'to', 'the', 'Medical', 'Intensive', 'Care', 'Unit', 'for', 'overnight', 'observation', 'because', 'of', 'her', 'somnolence', 'and', 'hypotension', '.', '11', '.', 'History', 'of', 'hemoptysis', ',', 'on', 'Coumadin', '.', 'There', 'be', 'ST', 'scoop', 'in', 'the', 'lateral', 'lead', 'consistent', 'with', 'Dig', 'vs.', 'a', 'question', 'of', 'chronic', 'ischemia', 'change', '.'] which all the words are generated together like a list. but i need them to be like sentence by sentence, the output format would be better like this: ['She be start on Levofloxacin but the patient become hypotensive at that point with blood pressure of 70/45 and receive a normal saline bolus to boost her blood pressure to 99/60 ; however the patient be admit to the Medical Intensive Care Unit for overnight observation because of her somnolence and hypotension .','11 . History of hemoptysis , on Coumadin .','There be ST scoop in the lateral lead consistent with Dig vs. a question of chronic ischemia change .'] can anyone help me please? thanks a lot
1
1
0
0
0
0
I have list of strings like this: ["Ola, Uber's India rival, invests $100M in scooter rental startup Vogo","Chattanooga startup Bellhops Moving raises over $31 million in latest", "Boston biotech Entrada launches with $59M to tackle deadly disease"] I want to identify strings like India, Boston, Chattanooga which is either city, town, country, state or continent from the list of strings and segregate them as per the region. I am not able to find a proper path or way to achieve this particular output. Any suggestions will be much helpful.
1
1
0
0
0
0
Basically, I want to reimplement this video. Given a corpus of documents, I want to find the terms that are most similar to each other. I was able to generate a cooccurrence matrix using this SO thread and use the video to generate an association matrix. Next I, would like to generate a second order cooccurrence matrix. Problem statement: Consider a matrix where the rows of the matrix correspond to a term and the entries in the rows correspond to the top k terms similar to that term. Say, k = 4, and we have n terms in our dictionary, then the matrix M has n rows and 4 columns. HAVE: M = [[18,34,54,65], # Term IDs similar to Term t_0 [18,12,54,65], # Term IDs similar to Term t_1 ... [21,43,55,78]] # Term IDs similar to Term t_n. So, M contains for each term ID, the most similar term IDs. Now, I would like to check how many of those similar terms match. In the example of M above, it seems that term t_0 and term t_1 are quite similar, because three out of four terms match, where as terms t_0 and t_nare not similar, because no terms match. Let's write M as a series of lists. M = [list_0, # Term IDs similar to Term t_0 list_1, # Term IDs similar to Term t_1 ... list_n] # Term IDs similar to Term t_n. WANT: C = [[f(list_0, list_0), f(list_0, list_1), ..., f(list_0, list_n)], [f(list_1, list_0), f(list_1, list_1), ..., f(list_1, list_n)], ... [f(list_n, list_0), f(list_n, list_1), ..., f(list_n, list_n)]] I'd like to find the matrix C, that has as its elements, a function f applied to the lists of M. f(a,b) measures the degree of similarity between two lists a and b. Going, with the example above, the degree of similarity between t_0 and t_1 should be high, whereas the degree of similarity of t_0 and t_n should be low. My questions: What is a good choice for comparing the ordering of two lists? That is, what is a good choice for function f? Is there a transformation already available that takes as an input a matrix like M and produces a matrix like C? Preferably a python package? Thank you, r0f1
1
1
0
0
0
0
I am trying to run the following code and it shows the error in the title. Does anybody know what is happening? import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, 3].values from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) imputer = imputer.fit(X[:, 1:3]) X[:, 1:3] = imputer.transform(X[:, 1:3]) X = pd.DataFrame(X) Y = pd.DataFrame(Y) from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
1
1
0
1
0
0
I'm trying to filter a pandas dataframe, which contains a column with news headlines (column name 'title'), based on whether each headline contains any of the company names from a list ('co_names_list') I've already tried the following attempt 1 sp500news = pd.DataFrame() for i in raw_news_2.index: for j in co_names_list: if j in raw_news_2.loc[i,'title']: sp500news = sp500news.append(raw_news_2.iloc[i]) print(sp500news) attempt 2 sp500news = raw_news_2.loc[raw_news_2['title'].isin(co_names_list)] Sample Dataframe
1
1
0
0
0
0
I am trying to do a task that is quite simple to do by a human: detect whether the first of two rows is a header row. Here's an example of sample inputs: Example1: yes name,age bob,12 Example2: yes first,last bob,jones Example3: no 1,2 8,hi Example4: no bob,jones tom,smith I'm a bit lost of where to begin to make an educated guess here. It doesn't have to be perfect (80% would be good), but what might be a good short-hand algorithm to determine the above? Some things I was thinking of: # header is usually always strings (wrong in case 4) for val in header: is val.replace(',','').replace('.','').replace('-','').isdigit(): header = False else: header = True
1
1
0
0
0
0
I want to create a new column for the text data (every row for that column is one description) after removing all numbers (such as 189, 98001), special characters ( ‘ , _, “, (, ) ), and letters with numbers or special characters (e21x16, e267, e4, e88889, entry778, id2, n27th, pv3, ). So I wrote the function below. However, the returned results still contain numbers, and special characters. Basically, my goal is to keep only English words, and abbreviations. Does anyone know why my function is not working. def standardize_text(df, text_field): df[text_field] = df[text_field].str.lower() df[text_field] = df[text_field].str.replace(r'(', '') df[text_field] = df[text_field].str.replace(r')', '') df[text_field] = df[text_field].str.replace(r',', '') df[text_field] = df[text_field].str.replace(r'_', '') df[text_field] = df[text_field].str.replace(r"'", "") df[text_field] = df[text_field].str.replace(r"^[a-z]+\[0-9]+$", "") df[text_field] = df[text_field].str.replace(r"^[0-9]{1,2,3,4,5}$", "") return df
1
1
0
0
0
0
Google Colab to reproduce the error None_for_gradient.ipynb I need a custom loss function where the value is calculated according to the model inputs, these inputs are not the default values (y_true, y_pred). The predict method works for the generated architecture, but when I try to use the train_on_batch, the following error appears. 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. My custom function of loss (below) was based on this example image_ocr.py#L475, in the Colab link has another example based on this solution Custom loss function y_true y_pred shape mismatch #4781, it also generates the same error: from keras import backend as K from keras import losses import keras from keras.models import TimeDistributed, Dense, Dropout, LSTM def my_loss(args): input_y, input_y_pred, y_pred = args return keras.losses.binary_crossentropy(input_y, input_y_pred) def generator2(): input_noise = keras.Input(name='input_noise', shape=(40, 38), dtype='float32') input_y = keras.Input(name='input_y', shape=(1,), dtype='float32') input_y_pred = keras.Input(name='input_y_pred', shape=(1,), dtype='float32') lstm1 = LSTM(256, return_sequences=True)(input_noise) drop = Dropout(0.2)(lstm1) lstm2 = LSTM(256, return_sequences=True)(drop) y_pred = TimeDistributed(Dense(38, activation='softmax'))(lstm2) loss_out = keras.layers.Lambda(my_loss, output_shape=(1,), name='my_loss')([input_y, input_y_pred, y_pred]) model = keras.models.Model(inputs=[input_noise, input_y, input_y_pred], outputs=[y_pred, loss_out]) model.compile(loss={'my_loss': lambda y_true, y_pred: y_pred}, optimizer='adam') return model g2 = generator2() noise = np.random.uniform(0,1,size=[10,40,38]) g2.train_on_batch([noise, np.ones(10), np.zeros(10)], noise) I need help to verify which operation is generating this error, because as far as I know the keras.losses.binary_crossentropy is differentiable.
1
1
0
0
0
0
If I have to use pretrained word vectors as embedding layer in Neural Networks (eg. say CNN), How do I deal with index 0? Detail: We usually start with creating a zero numpy 2D array. Later we fill in the indices of words from the vocabulary. The problem is, 0 is already the index of another word in our vocabulary (say, 'i' is index at 0). Hence, we are basically initializing the whole matrix filled with 'i' instead of empty words. So, how do we deal with padding all the sentences of equal length? One easy pop-up in mind is we can use the another digit=numberOfWordsInVocab+1 to pad. But wouldn't that take more size? [Help me!]
1
1
0
0
0
0
I'm having a problem in understanding how we got the Tf-Idf in the following program: I have tried calculating the value of a in the document 2 ('And_this_is_the_third_one.') using the concept given on the site, but my value of 'a' using the above concept is 1/26*log(4/1) ((count of occurrence of 'a' character)/(no of characters in the given document)*log( # Docs/ # Docs in which given character occurred)) = 0.023156 But output is returned as 0.2203 as can be seen in the output. from sklearn.feature_extraction.text import TfidfVectorizer corpus = ['This_is_the_first_document.', 'This_document_is_the_second_document.', 'And_this_is_the_third_one.', 'Is_this_the_first_document?', ] vectorizer = TfidfVectorizer(min_df=0.0, analyzer="char") X = vectorizer.fit_transform(corpus) print(vectorizer.get_feature_names()) print(vectorizer.vocabulary_) m = X.todense() print(m) I expected the output to be 0.023156 using the concept explained above. The output is: ['.', '?', '_', 'a', 'c', 'd', 'e', 'f', 'h', 'i', 'm', 'n', 'o', 'r', 's', 't', 'u'] {'t': 15, 'h': 8, 'i': 9, 's': 14, '_': 2, 'e': 6, 'f': 7, 'r': 13, 'd': 5, 'o': 12, 'c': 4, 'u': 16, 'm': 10, 'n': 11, '.': 0, 'a': 3, '?': 1} [[0.14540332 0. 0.47550697 0. 0.14540332 0.11887674 0.23775349 0.17960203 0.23775349 0.35663023 0.14540332 0.11887674 0.11887674 0.14540332 0.35663023 0.47550697 0.14540332] [0.10814145 0. 0.44206359 0. 0.32442434 0.26523816 0.35365088 0. 0.17682544 0.17682544 0.21628289 0.26523816 0.26523816 0. 0.26523816 0.35365088 0.21628289] [0.14061506 0. 0.57481012 0.22030066 0. 0.22992405 0.22992405 0. 0.34488607 0.34488607 0. 0.22992405 0.11496202 0.14061506 0.22992405 0.34488607 0. ] [0. 0.2243785 0.46836004 0. 0.14321789 0.11709001 0.23418002 0.17690259 0.23418002 0.35127003 0.14321789 0.11709001 0.11709001 0.14321789 0.35127003 0.46836004 0.14321789]]
1
1
0
0
0
0
I am working on a text classification problem where multiple text features and need to build a model to predict salary range. Please refer the Sample dataset Most of the resources/tutorials deal with feature extraction on only one column and then predicting target. I am aware of the processes such as text pre-processing, feature extraction (CountVectorizer or TF-IDF) and then the applying algorithms. In this problem, I have multiple input text features. How to handle text classification problems when multiple features are involved? These are the methods I have already tried but I am not sure if these are the right methods. Kindly provide your inputs/suggestion. 1) Applied data cleaning on each feature separately followed by TF-IDF and then logistic regression. Here I tried to see if I can use only one feature for classification. 2) Applied Data cleaning on all the columns separately and then applied TF-IDF for each feature and then merged the all feature vectors to create only one feature vector. Finally logistic regression. 3) Applied Data cleaning on all the columns separately and merged all the cleaned columns to create one feature 'merged_text'. Then applied TF-IDF on this merged_text and followed by logistic regression. All these 3 methods gave me around 35-40% accuracy on cross-validation & test set. I am expecting at-least 60% accuracy on the test set which is not provided. Also, I didn't understand how use to 'company_name' & 'experience' with text data. there are about 2000+ unique values in company_name. Please provide input/pointer on how to handle numeric data in text classification problem.
1
1
0
0
0
0
I am doing some NLP on a dataset and I am trying to remove stopwords. I am not using the nltk built in stopwords and I am using a custom stopwords list (which is about 10k words in different languages) I first defined the below function def clean_text(text): text = ''.join([word.lower() for word in text if word not in string.punctuation]) tokens = re.split('\W+', text) text = [lm.lemmatize(word) for word in tokens if word not in stopwords] return text then I applied it to the dataframe as follows: df_train['clean_text'] = df_train['question_text'].apply(lambda x: clean_text(x)) My Problem is that it is taking so long to process, so is there a faster way to do this?
1
1
0
1
0
0
I have list of sentence and I want to create skipgram (window size = 3) but I DONT want the counter to span across sentences since they are all unrelated. So, if I have the sentences: [["my name is John"] , ["This PC is black"]] the triplets will be: [my name is] [name is john] [this PC is] [PC is black] What is the best way to do it?
1
1
0
0
0
0
I am extracting ngrams from a corpus using nltk and python and I need to save the generated ngrams in a text file. I tried this code but no result: import nltk, re, string, collections from nltk.util import ngrams with open("titles.txt", "r", encoding='utf-8') as file: text = file.read() tokenized = text.split() Monograms = ngrams(tokenized, 1) MonogramFreq = collections.Counter(Monograms) with open('output.txt', 'w') as f: f.write(str(MonogramFreq)) here is a sample of titles.txt: Joli appartement s3 aux jardins de carthage mz823 Villa 600m2 haut standing à hammamet Hammem lif S2 manzah 7 Terrain constructible de 252m2 clôturé Terrain nu a gammarth Terrain agrecole al fahes Bureau 17 pièces Usine 5000m2 mannouba a simple print of MongramFreq must give something like this: ('atelier',): 17, ('430',): 17, ('jabli',): 17, ('mall',): 17, ('palmeraies',): 17, ('r4',): 17, ('dégagée',): 17, ('fatha',): 17 but output.txt file is not even created. I corrected my code as follows: import nltk, re, string, collections from nltk.util import ngrams with open("titles.txt", "r", encoding='utf-8') as file: text = file.read() tokenized = text.split() Threegrams = ngrams(tokenized, 3) ThreegramFreq = collections.Counter(Threegrams) for i in ThreegramFreq.elements(): with open('output.txt', 'a') as w: w.write(str(i)) w.close() Here is a sample of output.txt: ('les', 'étudiants', 'S1')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('Joli', 'appartement', 's3')('appartement', 's3', 'aux')('appartement', 's3', 'aux')('appartement', 's3', 'aux')('appartement', 's3', 'aux')('appartement', 's3', 'aux')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('s3', 'aux', 'jardins')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('aux', 'jardins', 'de')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage')('jardins', 'de', 'carthage') But I need to have the frequency of each 3-gram in my output.txt file. How to do ?
1
1
0
0
0
0
I am trying to get the JapaneseTokenizer working in python, but I am having trouble with one of the modules it depends on. Here is the trace of the errors I am getting: /Users/home/PycharmProjects/SubLingo/application/tokenizerTest.py Traceback (most recent call last): File "/Users/home/PycharmProjects/SubLingo/application/tokenizerTest.py", line 1, in <module> import JapaneseTokenizer File "/Users/home/PycharmProjects/SubLingo/venv/lib/python3.7/site-packages/JapaneseTokenizer/__init__.py", line 6, in <module> from JapaneseTokenizer.jumanpp_wrapper import JumanppWrapper File "/Users/home/PycharmProjects/SubLingo/venv/lib/python3.7/site-packages/JapaneseTokenizer/jumanpp_wrapper/__init__.py", line 1, in <module> from .jumanpp_wrapper import JumanppWrapper File "/Users/home/PycharmProjects/SubLingo/venv/lib/python3.7/site-packages/JapaneseTokenizer/jumanpp_wrapper/jumanpp_wrapper.py", line 2, in <module> from pyknp import Jumanpp ImportError: cannot import name 'Jumanpp' from 'pyknp' (/Users/home/PycharmProjects/SubLingo/venv/lib/python3.7/site-packages/pyknp/__init__.py) As you can see Jumanpp_wrapper is trying to import the module Jumanpp from pyknp. I have looked into the pyknp package currently installed on my machine and it does not have a module with this name. This leads me to conclude that the version of pyknp I have installed is not compatible with Jumanpp, so there must be another version available somewhere. The trouble is I install pyknp using the pip installer on my Mac, as recommended on the pyknp official site, so it should be the most current version. I'm not sure how to get an alternative version that contains the necessary module. I hope someone can point me in the right direction.
1
1
0
0
0
0
I am trying to use Whoosh to index a large corpus (roughly 25 million academic abstracts + titles). I marked the "abstract" field with vector=True because I need to be able to compute high scoring key terms based on the abstracts for similarity IR. However after about 4 million entries during indexing it crashed with the following error: Traceback (most recent call last): File "...", line 256, in <module> ... File "/home/nlp/*/anaconda3/envs/riken/lib/python3.6/site-packages/whoosh/writing.py", line 771, in add_document perdocwriter.add_vector_items(fieldname, field, vitems) File "/home/nlp/*/anaconda3/envs/riken/lib/python3.6/site-packages/whoosh/codec/whoosh3.py", line 244, in add_vector_items self.add_column_value(vecfield, VECTOR_COLUMN, offset) File "/home/nlp/*/anaconda3/envs/riken/lib/python3.6/site-packages/whoosh/codec/base.py", line 821, in add_column_value self._get_column(fieldname).add(self._docnum, value) File "/home/nlp/*/anaconda3/envs/riken/lib/python3.6/site-packages/whoosh/columns.py", line 678, in add self._dbfile.write(self._pack(v)) struct.error: 'I' format requires 0 <= number <= 4294967295 Schema: schema = Schema(title=TEXT(stored=False, phrase=False, field_boost=2.0, analyzer=my_analyzer, vector=True), abstract=TEXT(stored=False, phrase=False, analyzer=my_analyzer, vector=True), pmid=ID(stored=True), mesh_set=KEYWORD(stored=True, scorable=True), stored_title=STORED, stored_abstract=STORED) The index folder currently weights around 45GB. What exactly is the issue here? Is Whoosh simply not built to carry this amount of data?
1
1
0
0
0
0
I am trying to implement a code to check for the weather condition of a particular area using OpenWeatherMap API and NLTK to find entity name recognition. But I am not able to find the method of passing the entity present in GPE(that gives the location), in this case, Chicago, to my API request. Kindly help me with the syntax.The code to given below. Thank you for your assistance import nltk from nltk import load_parser import requests import nltk from nltk import word_tokenize from nltk.corpus import stopwords sentence = "What is the weather in Chicago today? " tokens = word_tokenize(sentence) stop_words = set(stopwords.words('english')) clean_tokens = [w for w in tokens if not w in stop_words] tagged = nltk.pos_tag(clean_tokens) print(nltk.ne_chunk(tagged))
1
1
0
0
0
0
I'm trying to implement the 'extract.subject_verb_object_triples' funcation from textacy on my dataset. However, the code I have written is very slow and memory intensive. Is there a more efficient implementation? import spacy import textacy def extract_SVO(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) tuples = textacy.extract.subject_verb_object_triples(doc) tuples_to_list = list(tuples) if tuples_to_list != []: tuples_list.append(tuples_to_list) tuples_list = [] sp500news['title'].apply(extract_SVO) print(tuples_list) Sample data (sp500news) date_publish \ 0 2013-05-14 17:17:05 1 2014-05-09 20:15:57 4 2018-07-19 10:29:54 6 2012-04-17 21:02:54 8 2012-12-12 20:17:56 9 2018-11-08 10:51:49 11 2013-08-25 07:13:31 12 2015-01-09 00:54:17 title 0 Italy will not dismantle Montis labour reform minister 1 Exclusive US agency FinCEN rejected veterans in bid to hire lawyers 4 Xis campaign to draw people back to graying rural China faces uphill battle 6 Romney begins to win over conservatives 8 Oregon mall shooting survivor in serious condition 9 Polands PGNiG to sign another deal for LNG supplies from US CEO 11 Australias opposition leader pledges stronger economy if elected PM 12 New York shifts into Code Blue to get homeless off frigid streets
1
1
0
0
0
0
I want to compute the Levenshtein distance between the sentences in one document. and I found a code that compute the distance in character level, but i want it to be in word-level. for instance, the output of this character level is 6, but i want it to be 1, which means only one word need to be deleted if we wanna change b to a or a to b : a = "The patient tolerated this ." b = "The patient tolerated ." def levenshtein_distance(a, b): if a == b: return 0 if len(a) < len(b): a, b = b, a if not a: return len(b) previous_row = range(len(b) + 1) for i, column1 in enumerate(a): current_row = [i + 1] for j, column2 in enumerate(b): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (column1 != column2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row print (previous_row[-1]) return previous_row[-1] result = levenshtein_distance(a, b)
1
1
0
0
0
0
I have a simple NLP problem, where I have some written reviews that have a simple binary positive or negative judgement. In this case I am able to train and test as independent variables the columns of X that contain the "bags of words", namely the single words in a sparse matrix. from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 300) #indipendent X = cv.fit_transform(corpus).toarray() #dependent y = dataset.iloc[:, 1].values ..and the dependent variable y, that is represented by the column 1 that assume values as 0 and 1( so basically positive and negative review). if instead of 0 and 1, I have reviews that can be voted from 1 to 5 stars should I proceed having an y variable column with values from 0 to 4?In other words I would lie to know how differ the model if instead of a binary good/bad review, the user has the possibility after his or her review to give a rating from 1 to 5. How is called this kind of problem in machine learning?
1
1
0
1
0
0
I'm currently writing a code to extract frequently used words from my csv file, and it works just fine until I get a barplot of strange words listed. I don't know why, probably because there are some foreign words involved. However, I don't know how to fix this. import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import train_test_split, KFold from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import matplotlib from matplotlib import pyplot as plt import sys sys.setrecursionlimit(100000) # import seaborn as sns %matplotlib inline %config InlineBackend.figure_format = 'retina' data = pd.read_csv("C:\\Users\\Administrator\\Desktop\ lp_dataset\\commitment.csv", encoding='cp1252',na_values=" NaN") data.shape data['text'] = data.fillna({'text':'none'}) def remove_punctuation(text): '' 'a function for removing punctuation''' import string #replacing the punctuations with no space, #which in effect deletes the punctuation marks translator = str.maketrans('', '', string.punctuation) #return the text stripped of punctuation marks return text.translate(translator) #Apply the function to each examples data['text'] = data['text'].apply(remove_punctuation) data.head(10) #Removing stopwords -- extract the stopwords #extracting the stopwords from nltk library sw= stopwords.words('english') #displaying the stopwords np.array(sw) # function to remove stopwords def stopwords(text): '''a function for removing stopwords''' #removing the stop words and lowercasing the selected words text = [word.lower() for word in text.split() if word.lower() not in sw] #joining the list of words with space separator return " ". join(text) # Apply the function to each examples data['text'] = data ['text'].apply(stopwords) data.head(10) # Top words before stemming # create a count vectorizer object count_vectorizer = CountVectorizer() # fit the count vectorizer using the text dta count_vectorizer.fit(data['text']) # collect the vocabulary items used in the vectorizer dictionary = count_vectorizer.vocabulary_.items() #store the vocab and counts in a pandas dataframe vocab = [] count = [] #iterate through each vocav and count append the value to designated lists for key, value in dictionary: vocab.append(key) count.append(value) #store the count in pandas dataframe with vocab as indedx vocab_bef_stem = pd.Series(count, index=vocab) #sort the dataframe vocab_bef_stem = vocab_bef_stem.sort_values(ascending = False) # Bar plot of top words before stemming top_vocab = vocab_bef_stem.head(20) top_vocab.plot(kind = 'barh', figsize=(5,10), xlim = (1000, 5000)) I want a list of frequent words ordered in a bar-plot, but for now it just gives non-English words with all-same frequency. Please help me out
1
1
0
0
0
0
I have a pre-trained word embedding with vectors of different norms, and I want to normalize all vectors in the model. I am doing it with a for loop that iterates each word and normalizes its vector, but the model us huge and takes too much time. Does gensim include any way to do this faster? I cannot find it. Thanks!!
1
1
0
0
0
0
I'm working on a reviews dataset. The problem is to fetch the important(number of times the same feature reviewed) positive and negative features of that specific product from the reviews. Ex: some xyz car positive: Great mileage, good looking, spacious etc Negative: Poor power, bad performance, software problems etc Thing is to extract the best and worst things about the product! Until now I've used gensim's doc2vec to find the top positive and negative sentence. The results are not so good and because it gets similar sentences with structure, not similar feathers it holds.
1
1
0
1
0
0
Trying to figure out a good way of solving this problem but wanted to ask for the best way of doing this. In my project, I am looking at multiple instrument note pairs for a neural network. The only problem is that there are multiple instruments with the same name and just because they have the same name doesn't mean that they are the same instrument 100% of the time. (It should be but I want to be sure.) I personally would like to analyze the instrument itself (like metadata on just the instrument in question) and not the notes associated with it. Is that possible? I should also mention that I am using pretty-midi to collect the musical instruments.
1
1
0
0
0
0
I am trying to run a neural network on text inputs. This is a binary classification. Here is my working code so far: df = pd.read_csv(pathname, encoding = "ISO-8859-1") df = df[['content_cleaned', 'meaningful']] #Content cleaned: text, meaningful: label X = df['content_cleaned'] y = df['meaningful'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=21) tokenizer = Tokenizer(num_words=100) tokenizer.fit_on_texts(X_train) X_train_encoded = tokenizer.texts_to_sequences(X_train) X_test_encoded = tokenizer.texts_to_sequences(X_test) max_len = 100 X_train = pad_sequences(X_train_encoded, maxlen=max_len) X_test = pad_sequences(X_test_encoded, maxlen=max_len) batch_size = 100 max_words = 100 input_dim = X_train.shape[1] # Number of features model = Sequential() model.add(layers.Dense(10, activation='relu', input_shape=X_train.shape[1:])) model.add(layers.Dense(1, activation='sigmoid')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(X_train, X_test, batch_size=batch_size, epochs=5, verbose=1, validation_split=0.1) My question is two parts. First is with the input_shape when creating the layers. I am confused as to the syntax of declaring this. When running this command: print(X_train.shape) I am getting this shape: (3609, 100). From my understanding, this is telling me that there are 3609 instances. From viewing other examples, my naive assumption was to use the 100 as there are 100 types (may be understanding this incorrectly) corresponding to the max_words that I initialized. I believe that I may have done the syntax incorrectly when initializing the input_shape. The second question is with an error message when running all of this (most likely with the incorrect input_shape). The error message highlights this line of code: validation_split=0.1) The error message is: ValueError: Error when checking target: expected dense_2 to have shape (None, 1) but got array with shape (1547, 1 Am I going about this problem incorrectly? I am very new to Deep Learning.
1
1
0
1
0
0
For the below sentence, I earned a dependency graph, and I transformed this dependency graph to a networkx graph. Now, I would like to find the shortest path between the words "Acute Kidney Injury" and "CYP3A4". Because "Acute Kidney Injury" has 3 nodes in the graph, I don't know, how I can find path between the aforementioned words. Below the dependency_graph of the sentence: Sentence: "Acute Kidney Injury from Excessive Potentiation of Calcium-channel Blocker via Synergistic CYP3A4 Inhibition by Clarithromycin Plus Voriconazole." Is there any way to do so?
1
1
0
0
0
0
I can use keras.layers.concatenate to concatenate two layers then send them to next layer, but if I want to take part of two layers then concatenate them and then send them to next layer, what should I do? For example, I want to take part of first conv layer and part of the second conv layer and the last pooling layer, and then concatenate them together to form one layer. But Keras is a high level library, how do we take part of them? You can understand me better by looking at the Figure 2 in paper A Network-based End-to-End Trainable Task-oriented Dialogue System.
1
1
0
0
0
0
I'm trying to train a model which in my opinion is taking too long compared to other datasets given that it's taking about 1h and 20min to complete one epoch. I think that the problem is because the dataset is not being stored on ram, but I'm not sure of this. The code is the following: def load_data(): train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) train_generator = train_datagen.flow_from_directory(path1, target_size=(200, 200), batch_size=32, class_mode="binary") test_datagen = ImageDataGenerator(rescale=1./255) test_generator = test_datagen.flow_from_directory(path2, target_size=(200, 200),batch_size=32, class_mode="binary") return train_generator, test_generator Model: Sequential model 2 Convolutional layers with 32 neurons, activation = relu. 1 Convolutional layer with 64 neurons, activation = relu. Flattening and Dense layer, activation = relu. Dropout of 0.5 Output layer (Dense) with sigmoid activation. Adam optimizer. Loss: binary cross entropy. Fit: model.fit_generator(x, steps_per_epoch=500, epochs=50, validation_data=y, validation_steps=len(y)/32, callbacks=[tensorboard]) My dataset has 1201 images and 2 classes. I built the model following this tutorial. My GPU is a GTX 1060 3gb. 8gb of ram. The images are being reshaped to 200x200. If you could help me I'd appreciate it. Thank you very much! EDIT: I've done what Matias Valdenegro suggested, even though it's true that the time it takes to complete an epoch is lower, what I realized is that it takes my GPU 10s to complete a step. This is what I really wanted to improve. Sorry for the confusion.
1
1
0
0
0
0
I am struggling with computing bag of words. I have a pandas dataframe with a textual column, that I properly tokenize, remove stop words, and stem. In the end, for each document, I have a list of strings. My ultimate goal is to compute bag of words for this column, I've seen that scikit-learn has a function to do that but it works on string, not on a list of string. I am doing the preprocessing myself with NLTK and would like to keep it that way... Is there a way to compute bag of words based on a list of list of tokens ? e.g., something like that: ["hello", "world"] ["hello", "stackoverflow", "hello"] should be converted into [1, 1, 0] [2, 0, 1] with vocabulary: ["hello", "world", "stackoverflow"]
1
1
0
0
0
0
I am trying to make a user-query based autosuggest. I have a bunch of aggregated queries like: QUERY COUNT "harry potter" 100 "iron man" 93 "harry pott" 32 "harr pott" 5 with around 200.000 rows. As you can see some users are extensively using the prefixed search typing in only the first letters of a word. Those queries in the example should be aggregated with a full "harry potter" row. Now assuming that the majority of users searches with full words, I think I can do that aggregation effectively (avoiding a nested for-loop over the whole index) in the following way: I sort the tokens in the query alphabetically and generate a map "first_token" like: "h" "harry potter" "ha" "harry potter" "har" "harry potter" "harr" "harry potter" "harry" "harry potter" and respectively "second_token" and so forth... "p" "harry potter" "po" "harry potter" "pot" "harry potter" "pott" "harry potter" "potte" "harry potter" "potter" "harry potter" and then I iterate from top to bottom and for each element like "harr pott" I check if there is an element in both "first_token" and "second_token" whose value is the same document, eg "harry potter" and that document is not identical to the original ("harr pott") and has a higher score, in which case I aggregate it. The runtime of this should be O(index_size * max_number_of_tokens). Now I was wondering if there is any lib for Python that can make it easier for me implementing all of this. Coming from Java/JS I am not so familiar with Python yet, I just know it has lots of tools for NLP. Can anything in NLTK or so help me? I think there should be at least a tool for vectorizing strings. Perhaps using that you can do the "starts-with" operation as a simple lookup without generating tries-maps manually?
1
1
0
0
0
0
I am trying to implement an AI to solve a simple task: move from A to B, while avoiding obstacles. So far I used pymunk and pygame to build the enviroment and this works quite fine. But now I am facing the next step: to get rewards for my reinforcement learning algorithm I need to detect the collision between the player and, for example, a wall. Or simply to restart the enviroment when a wall/obstacle gets hit. Setting the c_handler.begin function equals the Game.restart fuctions helped me to print out that the player actually hit something. But except from print() I can't access any other function concerning the player position and I don't really know what to do next. So how can i use the pymunk collision to restart the environment? Or are there other ways for resetting or even other libraries to build a proper enviroment? def restart(self, arbiter, data): car.body.position = 50, 50 return True def main(self): [...] c_handler = space.add_collision_handler(1,2) c_handler.begin = Game.restart [...]
1
1
0
0
0
0
Using gensim: from gensim.models import TfidfModel from gensim.corpora import Dictionary sent0 = "The quick brown fox jumps over the lazy brown dog .".lower().split() sent1 = "Mr brown jumps over the lazy fox .".lower().split() dataset = [sent0, sent1] vocab = Dictionary(dataset) corpus = [vocab.doc2bow(sent) for sent in dataset] model = TfidfModel(corpus) # To retrieve the same pd.DataFrame format. documents_tfidf_lol = [{vocab[word_idx]:tfidf_value for word_idx, tfidf_value in sent} for sent in model[corpus]] documents_tfidf = pd.DataFrame(documents_tfidf_lol) documents_tfidf.fillna(0, inplace=True) documents_tfidf [out]: dog mr quick 0 0.707107 0.0 0.707107 1 0.000000 1.0 0.000000 If we do the TF-IDF computation manually, sent0 = "The quick brown fox jumps over the lazy brown dog .".lower().split() sent1 = "Mr brown jumps over the lazy fox .".lower().split() documents = pd.DataFrame.from_dict(list(map(Counter, [sent0, sent1]))) documents.fillna(0, inplace=True, downcast='infer') documents = documents.apply(lambda x: x/sum(x)) # Normalize the TF. documents.head() # To compute the IDF for all words. num_sentences, num_words = documents.shape idf_vector = [] # Lets save an ordered list of IDFS w.r.t. order of the column names. for word in documents: word_idf = math.log(num_sentences/len(documents[word].nonzero()[0])) idf_vector.append(word_idf) # Compute the TF-IDF table. documents_tfidf = pd.DataFrame(documents.as_matrix() * np.array(idf_vector), columns=list(documents)) documents_tfidf [out]: . brown dog fox jumps lazy mr over quick the 0 0.0 0.0 0.693147 0.0 0.0 0.0 0.000000 0.0 0.693147 0.0 1 0.0 0.0 0.000000 0.0 0.0 0.0 0.693147 0.0 0.000000 0.0 If we use math.log2 instead of math.log: . brown dog fox jumps lazy mr over quick the 0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 1 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 It looks like gensim: remove the non-salient words from the TF-IDF model, it's evident when we print(model[corpus]) maybe the log base seem to be different from the log_2 maybe there's some normalization going on. Looking at https://radimrehurek.com/gensim/models/tfidfmodel.html#gensim.models.tfidfmodel.TfidfModel , the smart scheme difference would have output different values but it's not clear in the docs what is the default value. What is the default smartirs for gensim TfidfModel? What are the other default parameters that've caused the difference between a natively implemented TF-IDF and gensim's?
1
1
0
0
0
0
i am computing the levenshtein distance between the sentences, and now i have a text with several sentences. I don't know how to write the for loop to generate the distance between each pair of the sentence. sent = ['motrin 400-600 mg every 8 hour as need for pai . ', 'the depression : continue escitalopram ; assess need to change medication as an outpatient . ', 'Blood cltures from 11-30 grow KLEBSIELLA PNEUMONIAE and 12-01 grow KLEBSIELLA PNEUMONIAE and PROTEUS MIRABILIS both sensitive to the Meropenam which she have already be receive . '] def similarity(sent): feature_sim = [] for a,b in sent: feature_sim[a,b] = pylev.levenshtein(a,b) print (feature_sim)
1
1
0
0
0
0
I have the data like this : 0 1 251 TrCP 0 2 68 TrCP 0 3 61 TrCP 0 4 69 TrCP 0 5 70 TrCP 0 6 75 TrCP 0 7 63 TrCP 0 8 57 TrCP 0 9 96 TrCP 0 10 266 TrCP ........ 0 2827 62 TrNAP 1 1 67 TrCP 1 2 84 TrCP 1 3 159 TrCP 1 4 121 TrCP 1 5 80 TrCP 1 6 68 TrCP 1 7 148 TrCP 1 8 78 TrCP 1 9 71 TrCP 1 10 67 TrCP ........ 1 2827 76 TrNAP . . . 2828 1 62 TrCP In the first column, I have number from 0 - 2828. For each number in 0-2828 I wanna extract the last column (TrCP for example) according to the value in third column. For example, in the first column ='0', the max value in third column is '266', I wanna return the output: TrCP.
1
1
0
0
0
0
I have lots of CVs text documents. In that, there is different formats of dates are available e.g. Birthdate - 12-12-1995, Experience-year - 2000 PRESENT or 1995-2005 or 5 years of experience or 1995/2005, Date-of-Joining - 5th March, 2015 etc. From these data I want to extract only years of experience. How can I do this in Python using NLP? Please answer. I have tried with following : #This gives me all the dates from documents import datefinder data = open("/home/system/Desktop/samplecv/5c22fcad79fcc1.33753024.txt") str1 = ''.join(str(e) for e in data) matches = datefinder.find_dates(str1) for match in matches: print(match)
1
1
0
1
0
0
I have been trying to pull data from pantip.com including title, post stoy and all comments using beautifulsoup. However, I could pull only title and post stoy. I could not get comments. Here is code for title and post stoy import requests import re from bs4 import BeautifulSoup # specify the url url = 'https://pantip.com/topic/38372443' # Split Topic number topic_number = re.split('https://pantip.com/topic/', url) topic_number = topic_number[1] page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # Capture title elementTag_title = soup.find(id = 'topic-'+ topic_number) title = str(elementTag_title.find_all(class_ = 'display-post-title')[0].string) # Capture post story resultSet_post = elementTag_title.find_all(class_ = 'display-post-story')[0] post = resultSet_post.contents[1].text.strip() I tried to find by id elementTag_comment = soup.find(id = "comments-jsrender") according to I got the result below. elementTag_comment = <div id="comments-jsrender"> <div class="loadmore-bar loadmore-bar-paging"> <a href="javascript:void(0)"> <span class="icon-expand-left"><small>▼</small></span> <span class="focus- txt"><span class="loading-txt">กำลังโหลดข้อมูล...</span></span> <span class="icon-expand-right"><small>▼</small></span> </a> </div> </div> The question is how can I get all comments. Please, suggest me how to fix it.
1
1
0
0
0
0
I recently started to follow along with Siraj Raval's Deep Learning tutorials on YouTube, but I an error came up when I tried to run my code. The code is from the second episode of his series, How To Make A Neural Network. When I ran the code I got the error: Traceback (most recent call last): File "C:\Users\dpopp\Documents\Machine Learning\first_neural_net.py", line 66, in <module> neural_network.train(training_set_inputs, training_set_outputs, 10000) File "C:\Users\dpopp\Documents\Machine Learning\first_neural_net.py", line 44, in train self.synaptic_weights += adjustment ValueError: non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4) I checked multiple times with his code and couldn't find any differences, and even tried copying and pasting his code from the GitHub link. This is the code I have now: from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # We model a single neuron, with 3 input connections and 1 output connection. # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1 # and mean 0. self.synaptic_weights = 2 * random.random((3, 1)) - 1 # The Sigmoid function, which describes an S shaped curve. # We pass the weighted sum of the inputs through this function to # normalise them between 0 and 1. def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. # It indicates how confident we are about the existing weight. def __sigmoid_derivative(self, x): return x * (1 - x) # We train the neural network through a process of trial and error. # Adjusting the synaptic weights each time. def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): # Pass the training set through our neural network (a single neuron). output = self.think(training_set_inputs) # Calculate the error (The difference between the desired output # and the predicted output). error = training_set_outputs - output # Multiply the error by the input and again by the gradient of the Sigmoid curve. # This means less confident weights are adjusted more. # This means inputs, which are zero, do not cause changes to the weights. adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output)) # Adjust the weights. self.synaptic_weights += adjustment # The neural network thinks. def think(self, inputs): # Pass inputs through our neural network (our single neuron). return self.__sigmoid(dot(inputs, self.synaptic_weights)) if __name__ == '__main__': # Initialize a single neuron neural network neural_network = NeuralNetwork() print("Random starting synaptic weights:") print(neural_network.synaptic_weights) # The training set. We have 4 examples, each consisting of 3 input values # and 1 output value. training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_outputs = array([[0, 1, 1, 0]]) # Train the neural network using a training set # Do it 10,000 times and make small adjustments each time neural_network.train(training_set_inputs, training_set_outputs, 10000) print("New Synaptic weights after training:") print(neural_network.synaptic_weights) # Test the neural net with a new situation print("Considering new situation [1, 0, 0] -> ?:") print(neural_network.think(array([[1, 0, 0]]))) Even after copying and pasting the same code that worked in Siraj's episode, I'm still getting the same error. I just started out look into artificial intelligence, and don't understand what the error means. Could someone please explain what it means and how to fix it? Thanks!
1
1
0
0
0
0
I managed to install spacy but when trying to use nlp then I am getting a MemoryError for some weird reason. The code I wrote is as follows: import spacy import re from nltk.corpus import gutenberg def clean_text(astring): #replace newlines with space newstring=re.sub(" "," ",astring) #remove title and chapter headings newstring=re.sub("\[[^\]]*\]"," ",newstring) newstring=re.sub("VOLUME \S+"," ",newstring) newstring=re.sub("CHAPTER \S+"," ",newstring) newstring=re.sub("\s\s+"," ",newstring) return newstring.lstrip().rstrip() nlp=spacy.load('en') alice=clean_text(gutenberg.raw('carroll-alice.txt')) nlp_alice=list(nlp(alice).sents) The error I am getting is as follows The error message Although when my code is something like this then it works: import spacy nlp=spacy.load('en') alice=nlp("hello Hello") If anybody could point out what I am doing wrong I would be very grateful
1
1
0
0
0
0
I am trying to learn how to use Elmo embeddings via this tutorial: https://github.com/allenai/allennlp/blob/master/tutorials/how_to/elmo.md I am specifically trying to use the interactive mode as described like this: $ ipython > from allennlp.commands.elmo import ElmoEmbedder > elmo = ElmoEmbedder() > tokens = ["I", "ate", "an", "apple", "for", "breakfast"] > vectors = elmo.embed_sentence(tokens) > assert(len(vectors) == 3) # one for each layer in the ELMo output > assert(len(vectors[0]) == len(tokens)) # the vector elements correspond with the input tokens > import scipy > vectors2 = elmo.embed_sentence(["I", "ate", "a", "carrot", "for", "breakfast"]) > scipy.spatial.distance.cosine(vectors[2][3], vectors2[2][3]) # cosine distance between "apple" and "carrot" in the last layer 0.18020617961883545 My overall question is how do I make sure to use the pre-trained elmo model on the original 5.5B set (described here: https://allennlp.org/elmo)? I don't quite understand why we have to call "assert" or why we use the [2][3] indexing on the vector output. My ultimate purpose is to average the all the word embeddings in order to get a sentence embedding, so I want to make sure I do it right! Thanks for your patience as I am pretty new in all this.
1
1
0
1
0
0
I am trying to perform regression using a neural network to predict a single output from 146 input features. I applied Standard Scaling on all inputs and output. I monitor the Mean Absolute Error after training and it is unreasonably high on the train, validation and test sets (I am not even overfitting). I suspect this is due to the fact that the output variable is very imbalanced (see histogram). From the histogram it is possible to see that most of the samples are grouped around 0 but there is also another small group of samples around -5. Histogram of the imbalanced output This is model creation code: input = Input(batch_shape=(None, X.shape[1])) layer1 = Dense(20, activation='relu')(input) layer1 = Dropout(0.3)( layer1) layer1 = BatchNormalization()(layer1) layer2 = Dense(5, activation='relu', kernel_regularizer='l2')(layer1) layer2 = Dropout(0.3)(layer2) layer2 = BatchNormalization()(layer2) out_layer = Dense(1, activation='linear')(layer2) model = Model(inputs=input, outputs=out_layer) model.compile(loss='mean_squared_error', optimizer=optimizers.adam() , metrics=['mae']) This is the model summary: Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 146) 0 _________________________________________________________________ dense_1 (Dense) (None, 20) 2940 _________________________________________________________________ dropout_1 (Dropout) (None, 20) 0 _________________________________________________________________ batch_normalization_1 (Batch (None, 20) 80 _________________________________________________________________ dense_2 (Dense) (None, 5) 105 _________________________________________________________________ dropout_2 (Dropout) (None, 5) 0 _________________________________________________________________ batch_normalization_2 (Batch (None, 5) 20 _________________________________________________________________ dense_3 (Dense) (None, 1) 6 ================================================================= Total params: 3,151 Trainable params: 3,101 Non-trainable params: 50 _________________________________________________________________ Looking at the actual model predictions, the large error mainly happens for samples with a true output value around -5 (the small group of samples). I tried many configurations for the hyperparameters but still the error is very high. I see many suggestions on performing neural network classification on imbalanced data but what could be done with regression? It seems odd to me that a regression neural network is not learning this correctly. What am I doing wrong?
1
1
0
0
0
0
I've a text file with following text: The process runs very well|| It starts at 6pm and ends at 7pm|| The user_id is 23456|| This task runs in a daily schedule!! I'm trying to see extract all the lines that have the string "user_id". Basically I want to extract this: The user_id is 23456 My current python code only identify if the desired string exists (or not) in the text file: word = 'user_id' if word in open('text.txt').read(): print(word) else: print("Not found") How can I print all the sentences with that contains the word? Thanks!
1
1
0
0
0
0
I was attempting some preprocessing on nested list before attempting a small word2vec and encounter an issue as follow: corpus = ['he is a brave king', 'she is a kind queen', 'he is a young boy', 'she is a gentle girl'] corpus = [_.split(' ') for _ in corpus] [['he', 'is', 'a', 'brave', 'king'], ['she', 'is', 'a', 'kind', 'queen'], ['he', 'is', 'a', 'young', 'boy'], ['she', 'is', 'a', 'gentle', 'girl']] So the output above was given as a nested list & I intended to remove the stopwords e.g. 'is', 'a'. for _ in range(0, len(corpus)): for x in corpus[_]: if x == 'is' or x == 'a': corpus[_].remove(x) [['he', 'a', 'brave', 'king'], ['she', 'a', 'kind', 'queen'], ['he', 'a', 'young', 'boy'], ['she', 'a', 'gentle', 'girl']] The output seems indicating that the loop skipped to the next sub-list after removing 'is' in each sub-list instead of iterating entirely. What is the reasoning behind this? Index? If so, how to resolve assuming I'd like to retain the nested structure.
1
1
0
0
0
0
I am new in NLP (Natural Language Processing), I have installed NLTK on my computer and I have downloaded all the packages using nltk.download() My Script from nltk.tokenize import sent_tokenize example_text = "Hello Mr. Shan, how are you doing? the weather is quite cool today in Guwahati. I heard you are going to Delhi tomorrow." print(sent_tokenize(example_text)) Error C:\wamp64\www\python\NLTK>python test.py Traceback (most recent call last): File "test.py", line 1, in <module> from nltk.tokenize import sent_tokenize File "C:\Python27\lib\site-packages ltk\__init__.py", line 129, in <module> from nltk.collocations import * File "C:\Python27\lib\site-packages ltk\collocations.py", line 38, in <module > from nltk.util import ngrams File "C:\Python27\lib\site-packages ltk\util.py", line 10, in <module> import inspect File "C:\Python27\lib\inspect.py", line 39, in <module> import tokenize File "C:\wamp64\www\python\NLTK\tokenize.py", line 1, in <module> """Tokenization help for Python programs. File "C:\Python27\lib\site-packages ltk\tokenize\__init__.py", line 67, in <m odule> from nltk.tokenize.mwe import MWETokenizer File "C:\Python27\lib\site-packages ltk\tokenize\mwe.py", line 31, in <module > from nltk.util import Trie ImportError: cannot import name Trie
1
1
0
0
0
0
How can I create or load new language in spacy NLP ? for example spacy.load('tr') in python. editor jupyter. How can I create new entity but different entity ? for example FOOTBALL_CLUB. Please help me
1
1
0
0
0
0
I have a frequency value table like- a b 1 3 0 2 0 3 3 4 5 and I want to calculate the tf_idf. My code- l=len(data) for doc in data: m=data.groupby(doc).apply(lambda column: column.sum()/(column != 0).sum()) for i in range(l): tf=print(data.loc[i,doc]) idf=log(l/m) weight=tf*idf data.loc[i,doc]=weight Explanation- First I am iterating through each column where I am finding the non zero rows in that column in var m and storing the particular value of that row in column as tf and then calculating the tf_idf and replacing the values in table with tf_idf weights. expected output- for column g first row we have tf=3 idf=log(5/4) therefore tf_idf=idf*tf a b 1 0.4 0 2 0 0.4 3 0.17 .22
1
1
0
0
0
0
Is it possible to know in advance if CountVectorizer will throw ValueError: empty vocabulary? Basically, I have a corpus of documents and I'd like to filter out those that won't pass the CountVectorizer (I'm using stop_words='english') Thanks
1
1
0
0
0
0
Hi I am making a chatbot with python here is my code import sqlite3 import json from datetime import datetime def find_parent(pid): try: sql = "SELECT comment FROM parent_reply WHERE link_id = '{}' LIMIT 1".format(pid) c.execute(sql) result = c.fetchone() if result != None: return result[0] else: return False except Exception as e: print("find_parent", e) return False if __name__ == "__main__": create_table() row_counter = 0 paired_rows = 0 with open ("C:/Users/harry/OneDrive/Desktop/reddit_data/2007/RC_2007-11".format(timeframe.split('-')[0], timeframe), buffering=1000) as f: for row in f: row_counter =+ 1 row = json.loads(row) parent_id = row['parent_id'] body = format_data(row['body']) created_utc = row['score'] subreddit = row['subreddit'] parent_data = find_parent() and when I run that code I get the following error can anyone please help me parent_data = find_parent() TypeError: find_parent() missing 1 required positional argument: 'pid'
1
1
0
0
0
0
I am about to start working on a neural network for text generation. Inputs will be some words from a user (e.g. Brexit vote tomorrow chance of UK staying within EU slim) and the output will be a nice, well-written sentence (e.g. The Brexit vote will take place tomorrow and the UK is unlikely to stay within the European Union). For the implementation, I am thinking about a sequence2sequence model but, before starting to code, I would like to check whether this subject has not been addressed before. After many Google searches, it seems that nobody has done a similar project before (although there's a lot of papers about text translation), which surprises me because such a tool would be useful for many people, such as journalists, etc. Has any of you seen some useful Python code or relevant articles somewhere?
1
1
0
0
0
0
After running the code, the error is as follows: usage: text-summarizer.py [-h] [-l LENGTH] filepath text-summarizer.py: error: the following arguments are required: filepath I want to solve this issue by knowing how to input the file name to this piece of code mentioned : def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument("filepath", help="File name of text to summarize") parser.add_argument( "-l", "--length", default=4, help="Number of sentences to return" ) args = parser.parse_args() return args
1
1
0
0
0
0
Problem My goal is to apply Reinforcement Learning to predict the next state of an object under a known force in a 3D environment (the approach would be reduced to supervised learning, off-line learning). Details of my approach The current state is the vector representing the position of the object in the environment (3 dimensions), and the velocity of the object (3 dimensions). The starting position is randomly initialized in the environment, as well as the starting velocity. The action is the vector representing the movement from state t to state t+1. The reward is just the Euclidean distance between the predicted next state, and the real next state (I already have the target position). What have I done so far? I have been looking for many methods to do this. Deep Deterministic Policy Gradients works for a continuous action space, but in my case I also have a continuous state space. If you are interested in this approach, here's the original paper written at DeepMind: http://proceedings.mlr.press/v32/silver14.pdf The Actor-Critic approach should work, but it is usually (or always) applied to discrete and low-dimensional state space. Q-Learning and Deep-Q Learning cannot handle high dimensional state space, so my configuration would not work even if discretizing the state space. Inverse Reinforcement Learning (an instance of Imitation learning, with Behavioral Cloning and Direct Policy Learning) approximates a reward function when finding the reward function is more complicated than finding the policy function. Interesting approach, but I haven't seen any implementation, and in my case the reward function is pretty straightforward. Is there a methodology to deal with my configuration that I haven't explored?
1
1
0
1
0
0
I am following this documentation: https://github.com/deepmipt/DeepPavlov/blob/master/docs/components/classifiers.rst#id53 My code is the following: import os from deeppavlov import build_model, configs os.environ["KERAS_BACKEND"] = "tensorflow" CONFIG_PATH = configs.classifiers.intents_dstc2_big model = build_model(CONFIG_PATH, download=True) print(model(["Hello"])) I am expecting an output like this: "goals": {"pricerange": "cheap"}, "db_result": null, "dialog-acts": [{"slots": [["pricerange", "cheap"]], "act": "inform"}]} However, I am getting just an array of numbers like this: [[0.004440320190042257, 0.0035526982974261045, 0.003814868861809373, 0.004386670421808958, 0.0026496422942727804, 0.004122086800634861, 0.004859328735619783, 0.005762884858995676, 0.006169301923364401, 0.9743947386741638, 0.005218957085162401, 0.004720163065940142, 0.006856555584818125, 0.0047727120108902454, 0.008368589915335178, 0.011183635331690311, 0.007578883320093155, 0.005414197687059641, 0.008248056285083294, 0.005105976946651936, 0.005934832151979208, 0.005890967790037394, 0.005130860488861799, 0.005532102193683386, 0.005490032024681568, 0.0046647703275084496, 0.004590084310621023, 0.004707065410912037]] How should I properly display or use the output?
1
1
0
1
0
0
I have a dataset of ~10,000 rows of vehicles sold on a portal similar to Craigslist. The columns include price, mileage, no. of previous owners, how soon the car gets sold (in days), and most importantly a body of text that describes the vehicle (e.g. "accident free, serviced regularly"). I would like to find out which keywords, when included, will result in the car getting sold sooner. However I understand how soon a car gets sold also depends on the other factors especially price and mileage. Running a TfidfVectorizer in scikit-learn resulted in very poor prediction accuracy. Not sure if I should try including price, mileage, etc. in the regression model as well, as it seems pretty complicated. Currently am considering repeating the TF-IDF regression on a particular segment of the data that is sufficiently huge (perhaps Toyotas priced at $10k-$20k). The last resort is to plot two histograms, one of vehicle listings containing a specific word/phrase and another for those that do not. The limitation here would be that the words that I choose to plot will be based on my subjective opinion. Are there other ways to find out which keywords could potentially be important? Thanks in advance.
1
1
0
0
0
0
here is my python code def sentiment_local_file(text): """Detects sentiment in the local document""" language_client = language.Client() if isinstance(text, six.binary_type): text = text.decode('utf-8') with open("abhi.txt",'r') as fr: data = json.loads(fr.read()) print ([data['document']['content']]) document = language_client.document_from_text(data['document']['content']) result = document.annotate_text(include_sentiment=True, include_syntax=False, include_entities=False) I am trying to send list of strings in a single post request for analysis but it is giving an error . This is the text file i am reading. In above code text refer to file name and the code sample is a function { "document":{ "type":"PLAIN_TEXT", "language": "EN", "content":[ "pretending to be very busy" , "being totally unconcerned" , "a very superior attitude" , "calm, dignified and affectionate disposition" ]},"encodingType":"UTF8"} i read documentation and many examples still unable to figure it out.
1
1
0
0
0
0
I am doing a sentiment analysis project and firstly, I need to clean the text data. Some text contains Chinese, Tagalog and what I am doing now is trying to translate them to English. But until now, all the Chinese characters in this datafile have some Unicode representation like: <U+5C16> which could not be coped with using the Python Encoding&Decoding path. So I want to transform this kind of pattern to: \u5c16 Then I think we could use the following code to get the Chinese characters I want: text.encode('latin-1').decode('unicode_escape') So the question now is how to use the regex to transform <U+5C16> into\u5c16? Thank you very much! Update: I think the most difficult thing here is that I need to let the 5c16 part in \u5c16 be equivalent to the lowercase of the 5C16 in <U+5C16>. And in my social media dataset, what I see most is the text data like the following: <U+5C16><U+6C99><U+5480><U+9418><U+6A13> If I could transform the above text to '\u5c16\u6c99\u5480\u9418\u6a13' and print it in Python, I could get what I really want: 尖沙咀鐘樓 But how could I do this? Any insights and hints would be appreciated!
1
1
0
0
0
0
I have corpus and corpus_1, and both sizes are 1*3000, the first corpus is described as the 'Headline' and second corpus(corpus_1) describe as the 'text' of the Headline. how I can make only final corpus in pandas. Eg: "corpus_final = corpus + corpus_1"
1
1
0
0
0
0
I have multiple emails with a list of stock, price and quantity. Each day, the list is formatted a little differently and I was hoping to use NLP to try to understand read in the data and reformat it to show the information in a correct format. Here is a sample of the emails I receive: Symbol Quantity Rate AAPL 16 104 MSFT 8.3k 56.24 GS 34 103.1 RM 3,400 -10 APRN 6k 11 NP 14,000 -44 As we can see, the quantity is in varying formats, the ticker always is standard but the rate is either positive or negative or could have decimals. Another issue is that the headers are not always the same so that is not an identifier that I can rely on. So far I've seen some examples online where this works for names but I am unable to implement this for stock ticker, quantity and price. The code I've tried so far is below: import re import nltk from nltk.corpus import stopwords stop = stopwords.words('english') string = """ To: "Anna Jones" <anna.jones@mm.com> From: James B. Hey, This week has been crazy. Attached is my report on IBM. Can you give it a quick read and provide some feedback. Also, make sure you reach out to Claire (claire@xyz.com). You're the best. Cheers, George W. 212-555-1234 """ def extract_phone_numbers(string): r = re.compile(r'(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})') phone_numbers = r.findall(string) return [re.sub(r'\D', '', number) for number in phone_numbers] def extract_email_addresses(string): r = re.compile(r'[\w\.-]+@[\w\.-]+') return r.findall(string) def ie_preprocess(document): document = ' '.join([i for i in document.split() if i not in stop]) sentences = nltk.sent_tokenize(document) sentences = [nltk.word_tokenize(sent) for sent in sentences] sentences = [nltk.pos_tag(sent) for sent in sentences] return sentences def extract_names(document): names = [] sentences = ie_preprocess(document) for tagged_sentence in sentences: for chunk in nltk.ne_chunk(tagged_sentence): if type(chunk) == nltk.tree.Tree: if chunk.label() == 'PERSON': names.append(' '.join([c[0] for c in chunk])) return names if __name__ == '__main__': numbers = extract_phone_numbers(string) emails = extract_email_addresses(string) names = extract_names(string) print(numbers) print(emails) print(names) This code does a good job with numbers, emails and names but I am unable to replicate this for the example I have and do not really know how to go about it. Any tips will be more than helpful.
1
1
0
1
0
0
Sorry but title doesnt really make sense i am trying to make an ai that clicks on the ball to make it bounce. for context heres a picture of the application in the game when you click the ball it goes up and then comes back down and the aim of the game is to keep it up. i have writen some code that turns the image into a mask with opencv, heres a picture of the result what i now need to do is find the location of the ball in pixels/coordinates so i can make the mouse move to it and click it. By the way the ball has a margin on the left and right of it so it doesn't just go strait up and down but left and right too. Also the ball isnt animated,just a moving image. How would i get the ball location in pixels/coordinates so i can move the mouse to it. heres a copy of my code: import numpy as np from PIL import ImageGrab import cv2 import time import pyautogui def draw_lines(img,lines): for line in lines: coords = line[0] cv2.line(img, (coords[0], coords[1]), (coords[2], coords[3]), [255,255,255], 3) def process_img(original_image): processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300) vertices = np.array([[0,0],[0,800],[850,800],[850,0] ], np.int32) processed_img = roi(processed_img, [vertices]) # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html # edges rho theta thresh # min length, max gap: lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15) draw_lines(processed_img,lines) return processed_img def roi(img, vertices): #blank mask: mask = np.zeros_like(img) # fill the mask cv2.fillPoly(mask, vertices, 255) # now only show the area that is the mask masked = cv2.bitwise_and(img, mask) return masked def main(): last_time = time.time() while(True): screen = np.array(ImageGrab.grab(bbox=(0,40, 800, 850))) new_screen = process_img(screen) print('Loop took {} seconds'.format(time.time()-last_time)) last_time = time.time() cv2.imshow('window', new_screen) #cv2.imshow('window2', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break def mouse_movement(): ##Set to move relative to where ball is pyautogui.moveTo(300,400) pyautogui.click(); main() Sorry if this is confusing but brain.exe has stopped working :( Thanks
1
1
0
0
0
0
I have a large amount of text that includes wikipedia articles, news articles, etc. About 1.5 billion words total, and about 3 million unique words. What I want to do is decide when to count to consecutive words as a single word, for example "orange juice" should probably be treated as a single word. To decide if a pair of words should be treated as a single word, I need to know how many times the bigram occurs, and how many times each of the words in the bigram occurs. bigramCount/(word1Count*word2Count) > threshold The problem is that a variable containing all the bigram counts of my text would occupy more memory than my computer ram size. What I tried doing is: 1. Count single words 2. For every single word: 1. Count every ocurrence of a bigram that starts with that word 2. Decide, applying the formula, which of those bigrams should be treated as a single word. That way it's easier on the memory, but it takes too long to do that. I'm currently doing that but it has been running for at least a day now, so I'm trying to come up with a better way of doing this. Any idea?
1
1
0
0
0
0
How can we use ANN to find some similar documents? I know its a silly question, but I am new to this NLP field. I have made a model using kNN and bag-of-words approach to solve my problem. Using that I can get n number of documents (along with their closeness) that are somewhat similar to the input, but now I want to implement the same using ANN and I am not getting any idea. Thanks in advance for any help or suggestions.
1
1
0
1
0
0
I am working on an Address parsing project where, I need to detect various components of the address, such as city, state, postal_code, street_no etc. I wrote a regular expression to filter out the postal codes handling all user inputs. sample_add = "16th main road btm layout 560029 5-6-00-76 56 00 78 560-029 25 -000-1" regexp = re.compile(r"([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])") print(re.findall(regexp, sample_add)) Output :- [560029, 560076, 560078, 560029, 250001] This is able to identify postal_codes for such addresses, However, when an address like the following comes, it combines the Street nos and interprets it as the postal code, Ex. `sample_add_2 = "House no 323/46 16th main road, btm layout, bengaluru 560029" In this case, the postal code is identified as 323461, while the correct one should have been 560029.
1
1
0
0
0
0
I am developing an auto encoder by using tensor flow. While calculating the loss function I encountered an error saying that the dimensions must be equal to find the mean. So I displayed the shape of input layer and output layer and both were different.I couldn't analyze where the problem is. The shapeof the image used in the dataset is (54,96,3) Here is my code ##-------------------------------------------- import cv2 as cv import numpy as np import tensorflow as tf import argparse import os import glob import matplotlib import matplotlib.pyplot as plt from functools import partial def load_images_from_folder(folder): images = [] for filename in os.listdir(folder): img = cv.imread(os.path.join(folder,filename)) if img is not None: images.append(img) return np.asarray(images) def plot_image(image, cmap = "Greys_r"): plt.imshow(image.reshape([54, 96, 3]).astype(np.uint8), cmap=cmap,interpolation="nearest") plt.axis("off") def _parse_function(filename): image_string = tf.read_file(filename) image_decoded = tf.image.decode_jpeg(image_string, channels=3) image = tf.cast(image_decoded, tf.float32) return image ## Parameters n_inputs = 96 * 54 BATCH_SIZE = 150 batch_size = tf.placeholder(tf.int64) files = list(glob.glob(os.path.join('danceVideoFrame1','*.*'))) dataset = tf.data.Dataset.from_tensor_slices((files)) dataset = dataset.map(_parse_function) dataset = dataset.batch(BATCH_SIZE) iterator = dataset.make_one_shot_iterator() features = iterator.get_next() with tf.Session() as sess: #print(sess.run(features).shape) #plot_image(sess.run(features), cmap = "Greys_r") #plt.show() ## Encoder n_hidden_1 = 300 n_hidden_2 = 150 # codings ## Decoder n_hidden_3 = n_hidden_1 n_outputs = n_inputs learning_rate = 0.01 l2_reg = 0.0001 ## Define the Xavier initialization xav_init = tf.contrib.layers.xavier_initializer() ## Define the L2 regularizer l2_regularizer = tf.contrib.layers.l2_regularizer(l2_reg) ## Create the dense layer dense_layer = partial(tf.layers.dense, activation=tf.nn.elu, kernel_initializer=xav_init, kernel_regularizer=l2_regularizer) ## Make the mat mul hidden_1 = dense_layer(features, n_hidden_1) hidden_2 = dense_layer(hidden_1, n_hidden_2) hidden_3 = dense_layer(hidden_2, n_hidden_3) outputs = dense_layer(hidden_3, n_outputs, activation=None) print (outputs.shape) print (features.shape) #loss function loss = tf.reduce_mean(tf.square(outputs - features)) ## Optimize loss = tf.reduce_mean(tf.square(outputs - features)) optimizer = tf.train.AdamOptimizer(learning_rate) train = optimizer.minimize(loss) output: $ python computery_dance.py 2019-01-11 03:11:14.446355: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 (?, ?, ?, 5184) (?, ?, ?, 3) Traceback (most recent call last): File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1628, in _create_c_op c_op = c_api.TF_FinishOperation(op_desc) tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimensions must be equal, but are 5184 and 3 for 'sub' (op: 'Sub') with input shapes: [?,?,?,5184], [?,?,?,3]. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "computery_dance.py", line 88, in <module> loss = tf.reduce_mean(tf.square(outputs - features)) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 866, in binary_op_wrapper return func(x, y, name=name) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 8912, in sub "Sub", x=x, y=y, name=name) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper op_def=op_def) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 488, in new_func return func(*args, **kwargs) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3274, in create_op op_def=op_def) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1792, in __init__ control_input_ops) File "C:\Users\J MANOJ\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1631, in _create_c_op raise ValueError(str(e)) ValueError: Dimensions must be equal, but are 5184 and 3 for 'sub' (op: 'Sub') with input shapes: [?,?,?,5184], [?,?,?,3].
1
1
0
1
0
0
I have a large English corpus named SubIMDB and I want to make a list of all the words with their frequency. Meaning that how much they have appeared in the whole corpus. This frequency list should have some characteristics: The words like boy and boys or other grammatical features such as get and getting, the same word or lemma and if there are 3 boy and 2 boys it should list them as Boy 5. However, not for the cases like Go and Went which have irregular forms(or foot and feet) I want to use this frequency list as a kind of dictionary so whenever I see a word in another part of the program I want to check its frequency in this list. So, better if it is searchable without looking up all the of it. My questions are: For the first problem, what should I do? Lemmatize? or Stemming? or how can I get that? For second, what kind of variable type I should set it to? like dictionary or lists or what? Is is the best to save it in csv? Is there any prepared toolkit for python doing this all? Thank you so much.
1
1
0
0
0
0
txt1_response = requests.get("http://www.gutenberg.org/cache/epub/11313/pg11313.txt") txt1 = txt1_response.text I've read all the text from this url. I want to delete all the text content before the words "ABOUT ANIMALS." What is the best way to do this?
1
1
0
0
0
0
Coming from a programming background where you write code, test, deploy, run.. I'm trying to wrap my head around the concept of "training a model" or a "trained model" in data science, and deploying that trained model. I'm not really concerned about the deployment environment, automation, etc.. I'm trying to understand the deployment unit.. a trained model. What does a trained model look like on a file system, what does it contain? I understand the concept of training a model, and splitting a set of data into a training set and testing set, but lets say I have a notebook (python / jupyter) and I load in some data, split between training/testing data, and run an algorithm to "train" my model. What is my deliverable under the hood? While I'm training a model I'd think there'd be a certain amount of data being stored in memory.. so how does that become part of the trained model? It obviously can't contain all the data used for training; so for instance if I'm training a chatbot agent (retrieval-based), what is actually happening as part of that training after I'd add/input examples of user questions or "intents" and what is my deployable as far as a trained model? Does this trained model contain some sort of summation of data from training or array of terms, how large (deployable size) can it get? While the question may seem relatively simple "what is a trained model", how would I explain it to a devops tech in simple terms? This is an "IT guy interested in data science trying to understand the tangible unit of a trained model in a discussion with a data science guy". Thanks
1
1
0
1
0
0
I'm taking input from the user and then tokenizing it, tokenization is successful but the problem i'm facing is it does not display anything i am trying to search the words in xlsx file which user inputs and then it should display that complete row in which that specific word exists. import xlrd import pandas as pd from openpyxl import load_workbook from xlrd import open_workbook from nltk import word_tokenize sen = input("Enter your sentence: ") sent = word_tokenize(sen) print(sent) book = open_workbook("Pastho dictionary.xlsx") for sheet in book.sheets(): for rowidx in range(sheet.nrows): row = sheet.row(rowidx) for colidx,cell in enumerate(row): for i in sent: if cell.value == sent:#row value print ("Found Row Element") print(rowidx, colidx) print(cell.value) print(row) i expect all the input words to be searched and then display the entire row in which that word exists.
1
1
0
0
0
0
I am relatively new to Python and very new to NLP (and nltk) and I have searched the net for guidance but not finding a complete solution. Unfortunately the sparse code I have been playing with is on another network, but I am including an example spreadsheet. I would like to get suggested steps in plain English (more detailed than I have below) so I could first try to script it myself in Python 3. Unless it would simply be easier for you to just help with the scripting... in which case, thank you. Problem: A few columns of an otherwise robust spreadsheet are very unstructured with anywhere from 500-5000 English characters that tell a story. I need to essentially make it a bit more structured by pulling out the quantifiable data. I need to: 1) Search for a string in the user supplied unstructured free text column (The user inputs the column header) (I think I am doing this right) 2) Make that string a NEW column header in Excel (I think I am doing this right) 3) Grab the number before the string (This is where I am getting stuck. And as you will see in the sheet, sometimes there is no space between the number and text and of course, sometimes there are misspellings) 4) Put that number in the NEW column on the same row (Have not gotten to this step yet) I will have to do this repeatedly for multiple keywords but I can figure that part out, I believe, with a loop or something. Thank you very much for your time and expertise...
1
1
0
0
0
0
I need to create a dataframe from a loop. the idea is that the loop will read a data frame of texts (train_vs) and search for specific key words ['govern', 'data'] and then calculate their frequency or TF. what I want is an outcome of two columns with the TF of the words for each text inside them. the code I am using is the following: d = pd.DataFrame() key = ['govern', 'data'] for k in key: for w in range(0, len(train_vs)): wordcount = Counter(train_vs['doc_text'].iloc[w]) a_vs = (wordcount[k]/len(train_v.iloc[w])*1) temp = pd.DataFrame([{k: a_vs}] ) d = pd.concat([d, temp]) however, I am getting two columns but with values for the first key word and nan for second for the whole texts column and then nan for the first and values for the second again for the whole texts column. so the number of the rows of the outcome dataframe is double. I want to have both values next to each other. Your help is highly appreciated. Thanks.
1
1
0
0
0
0
I was trying to write a code for tokenization of strings in python for some NLP and came up with this code: str = ['I am Batman.','I loved the tea.','I will never go to that mall again!'] s= [] a=0 for line in str: s.append([]) s[a].append(line.split()) a+=1 print(s) the output came out to be: [[['I', 'am', 'Batman.']], [['I', 'loved', 'the', 'tea.']], [['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]] As you can see, the list now has an extra dimension, for example, If I want the word 'Batman', I would have to type s[0][0][2] instead of s[0][2], so I changed the code to: str = ['I am Batman.','I loved the tea.','I will never go to that mall again!'] s= [] a=0 m = [] for line in str: s.append([]) m=(line.split()) for word in m: s[a].append(word) a += 1 print(s) which got me the correct output: [['I', 'am', 'Batman.'], ['I', 'loved', 'the', 'tea.'], ['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']] But I have this feeling that this could work with a single loop, because the dataset that I will be importing would be pretty large and a complexity of n would be a lot better that n^2, so, is there a better way to do this/a way to do this with one loop?
1
1
0
0
0
0
I am new to Pandas. My goal is to detect the wrong element in a fixed column and return that row value Here is the sample scenario 45 dollar is the wrong element in the country column. so i want to detect this value and return the row number(if possible) in my program. My first thought was to create a list and match with this or do i need to search NLP solution here. Kindly help me to solve it out
1
1
0
0
0
0
Is there a way (Pattern or Python or NLTK, etc) to detect of a sentence has a list of words in it. i.e. The cat ran into the hat, box, and house. | The list would be hat, box, and house This could be string processed but we may have more generic lists: i.e. The cat likes to run outside, run inside, or jump up the stairs. | List=run outside, run inside, or jump up the stairs. This could be in the middle of a paragraph or the end of the sentence which further complicates things. I've been working with Pattern for python for awhile and I'm not seeing a way to go about this and was curious if there is a way with pattern or nltk (natural language tool kit).
1
1
0
0
0
0
Here's my data set in a bank1.txt file Keyword:Category ccn:fintech credit:fintech smart:fintech Here's my data set in a bank2.txt file Keyword:Category mcm:mcm switching:switching pul-sim:pulsa transfer:transfer debit sms:money transfer What I want to do Keyword Category_all mcm mcm switching switching pul-sim pulsa transfer transfer debit sms money transfer ccn fintech credit fintech smart fintech What l did is with open('entity_dict.txt') as f: //bank.txt content = f.readlines() content = [x.strip() for x in content ] def ambil(inp): try: out = [] for x in content: if x in inp: out.append(x) if len(out) == 0: return 'other' else: output = ' '.join(out) return output except: return 'other' frame_institution['Keyword'] = frame_institution['description'].apply(ambil) fintech = pd.read_csv('bank.txt', sep=":") frame_Keyword = pd.merge(frame_institution, fintech, on='Keyword') Then for bank2.txt code is with open('entity_dict2.txt') as f: content2 = f.readlines() content2 = [x.strip() for x in content2 ] def ambil2(inp): try: out = [] for x in content2: if x in inp: out.append(x) if len(out) == 0: return 'other' else: output = ' '.join(out) return output except: return 'other' frame_institution['Keyword2'] = frame_institution['description'].apply(ambil2) fintech2 = pd.read_csv('bank2.txt', sep=":") frame_Keyword2 = pd.merge(frame_institution, fintech, on='Keyword') frame_Keyword2 = pd.merge(frame_Keyword2, fintech2, on='Keyword2') Then l do filter for some keywords: frame_Keyword2[frame_Keyword2['category_all'] == 'pulsa'] Actually result is: Keyword Category_all mcm mcm switching switching ccn fintech credit fintech smart fintech But there is no 'pulsa', 'transfer', and 'money transfer' appear in Category_all. l think there is a better way to solve it. `
1
1
0
0
0
0