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 am doing a ANN in Python and I am looking for the best parameters for my ANN with GridSearchCV (sklearn). The problem is that each time, "best_parameters" attribute returns the first element of each parameter (so if I change the order of my elements, then the return is different). Here is my code : # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV # Importing the dataset dataset = pd.read_csv('data.csv') X = dataset.iloc[:, 17:27].values y = dataset.iloc[:, 3].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Find best parameters def build_classifier(optimizer): # Init ANN classifier = Sequential() # Add input and first hidden layers classifier.add(Dense(units=6, activation="relu", kernel_initializer="uniform", input_dim=10)) # Add another hidder layer classifier.add(Dense(units=6, activation="relu", kernel_initializer="uniform")) # Add output layer classifier.add(Dense(units=1, activation="sigmoid", kernel_initializer="uniform")) # Compile ANN classifier.compile(optimizer=optimizer, loss="mean_squared_error") return classifier # Looking for best parameters with GridSearchCV classifier = KerasClassifier(build_fn=build_classifier) parameters = {"batch_size":[1, 5, 10], "epochs":[100,200], "optimizer": ["rmsprop", "sgd", "adam"]} grid_search = GridSearchCV(estimator=classifier, param_grid=parameters, scoring="neg_mean_squared_error", cv=10) grid_search = grid_search.fit(X_train, y_train) best_parameters = grid_search.best_params_ best_precision = grid_search.best_score_ So in the line parameters = {"batch_size":[1, 5, 10], "epochs":[100,200], "optimizer": ["rmsprop", "sgd", "adam"]} I have the parameters I want to try, and the attribute "best_parameters" always returns the first element of each parameter (check the picture where I try several orders for the parameters). best_parameters return according to parameter order I don't understand where this comes from and how to correct it.
1
1
0
0
0
0
I am trying to finish a question and it asks me to parse a sentence using the shift-reduce parser and it's default grammar. It asks me to parse a sentence as many different ways as possible and asks for the number of different trees. Can anyone know what does that mean with an example if possible please? I thought there was only one tree that would satisfy the sentence?
1
1
0
0
0
0
I need to calculate and store cosine distances for all pairs of words of a word2vec encoding. Each word is represented as a 4 * 1 vector stored in a pandas dataframe, with each element in the contunuous range [1, 9]. I need to store the result in a pandas dataframe so that it can be accessed in constant time. I am unable to use the apply function of pandas library/lambda. Using nested loops will take approx. 9 hours (according to tqdm). word word1 word2 word3 ... word1 d11 d12 d13... word2 d21 d22 d23... word3 d31 d32 d33... . . .
1
1
0
0
0
0
I am using the python wrapper of NLP Stanford's SUTime. So far comparing the results to other date parsers like duckling, dateparser's search_dates, parsedatetime and natty, SUTime gives the most reliable results. However, it fails to capture some obvious dates from documents. Following are the 2 types of documents that I am having difficult parsing for dates using SUTime. I am out and I won't be available until 9/19 I am out and I won't be available between (September 18-September 20) It gives no results in case of the first document. However, for the second document, it only captures the month but not the date or date range. I tried wrapping my head around the java's code to see if I could alter or add some rules to make this work, but couldn't figure it out. If someone can suggest a way to make this work with SUTime, it would be really helpful. Also, I tried dateparser's search_dates, and it is unreliable as it captures anything and everything. Like for the first document it would parse a date on text "am out" (which is not required) and "9/19" (which is okay). So if there is a way to control this behavior it would work as well.
1
1
0
0
0
0
I am currently processing texts with the NLP library Spacy. Spacy, however, does not lemmatize all words correctly, therefore I want to extend the lookup table. Currently I am merging Spacy's constant lookup table with my extension and subsequently overwrite Spacy's native lookup table. I have the feeling, however, that this approach may not be the best and most consistent one. Question: Is there another possibility to update the lookup table in Spacy, e.g. an update or extend function? I have read the Docs and could not find something like that. Or is this approach "just fine"? Working example of my current approach: import spacy nlp = spacy.load('de') Spacy_lookup = spacy.lang.de.LOOKUP New_lookup = {'AAA':'Anonyme Affen Allianz','BBB':'Berliner Bauern Bund','CCC':'Chaos Chaoten Club'} Spacy_lookup.update(New_lookup) spacy.lang.de.LOOKUP = Spacy_lookup tagged = nlp("Die AAA besiegt die BBB und den CCC unverdient.") [ print(each.lemma_) for each in tagged] Die Anonyme Affen Allianz besiegen der Berliner Bauern Bund und der Chaos Chaoten Club unverdient .
1
1
0
0
0
0
Is there a way I can hack somehow an xbox controller to send custom signal or clone the protocol with a usb dongle. Basically a way I can use my pc as a controller for xbox console. I am trying to develop an AI that plays FIFA and all the processing is made on PC. I can't find how to send the signal, corresponding to the action the AI has decided to make, to the xbox console. Thank you in advance
1
1
0
0
0
0
The problem is i need to load the file which i have in h5 format as below from keras.models import load_model model = load_model('my_model.h5') model.compile(loss='categorical_crossentropy',optimizer='rmsprop',metrics=['acc']) classes = model.predict_classes("How is the weather today") print classes And also i need that percentage value of the prediction to be printed Here is the link that i refered to while generating this model and saving the file
1
1
0
0
0
0
I am new in Python and have a text file "in_file.txt" with sentences in_file = ['sentence one', 'sentence two', 'sentence has the word bad one', 'sentence four', 'sentence five', 'sentence six', 'sentence seven', 'sentence has the word bad two', 'sentence nine'] Among these, there are sentences with the word "bad" in them exactly once. I want to take the above 5 sentences of any line with the word "bad" in it and make a paragraph with them as follows (except at the beginning where there may not be 5 sentences present): out_file = ['sentence one sentence two', 'sentence has the word bad sentence four sentence five sentence six sentence seven'] Then save it in a file "out_file.txt". Thank you for help and please let me know if I did not provide enough explanation. Please note that maybe all the sentences in the input file do not make it to the final selection in the output file. I'm only interested in those sentences being above and within 5 sentences of another sentence with the word "bad" in it. Just a starting point: with open("in_file.txt", "r") as lines: for line in lines # maybe there is an index counter here! for word in line if word = bad # then take the above 5 lines # add to the out_file # return out_file
1
1
0
0
0
0
I can't seem to find an answer to my exact problem. Can anyone help? A simplified description of my dataframe ("df"): It has 2 columns: one is a bunch of text ("Notes"), and the other is a binary variable indicating if the resolution time was above average or not ("y"). I did bag-of-words on the text: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(lowercase=True, stop_words="english") matrix = vectorizer.fit_transform(df["Notes"]) My matrix is 6290 x 4650. No problem getting the word names (i.e. feature names) : feature_names = vectorizer.get_feature_names() feature_names Next, I want to know which of these 4650 are most associated with above average resolution times; and reduce the matrix I may want to use in a predictive model. I do a chi-square test to find the top 20 most important words. from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 selector = SelectKBest(chi2, k=20) selector.fit(matrix, y) top_words = selector.get_support().nonzero() # Pick only the most informative columns in the data. chi_matrix = matrix[:,top_words[0]] Now I'm stuck. How do I get the words from this reduced matrix ("chi_matrix")? What are my feature names? I was trying this: chi_matrix.feature_names[selector.get_support(indices=True)].tolist() Or chi_matrix.feature_names[features.get_support()] These gives me an error: feature_names not found. What am I missing? A
1
1
0
0
0
0
By the documentation I read that a dummy classifier can be used to test it against a classification algorithm. This classifier is useful as a simple baseline to compare with other (real) classifiers. Do not use it for real problems. What does the dummy classifier do when it uses the stratified aproach. I know that the docummentation says that: generates predictions by respecting the training set’s class distribution. Could anybody give me a more theorical explanation of why this is a proof for the performance of the classifier?.
1
1
0
1
0
0
I am training a doc2vec model with multiple tags, so it includes the typical doc "ID" tag and then it also contains a label tag "Category 1." I'm trying to graph the results such that I get the doc distribution in a 2d (using LargeVis) but am able to color different tags. My problem is that the vectors the model returns exceed the number of training observations by 5 making difficult to align the original tags with the vectors: In[1]: data.shape Out[1]: (17717,5) Training the model on 100 parameters In[2]: model.docvecs.doctag_syn0.shape Out[2]: (17722,100) I have no idea whether the 5 additional observations shift the order of the vectors or whether they're just appended to the end. I want to avoid using string tags for the doc IDs because I am preparing this code to use on a much larger dataset. I found an explanation in a google group https://groups.google.com/forum/#!topic/gensim/OdvQkwuADl0 which explained that using multiple tags per doc can result in this type of output. However, I haven't been able to find a way to avoid or correct it in any forum or documentation.
1
1
0
1
0
0
I want to classify handwritten digits(MNIST) with a simple Python code. My method is a simple single layer perceptron and i do it with batch method. My problem is that for example, If I train digit "1" and then then other digits, networks always shows result for "1". In fact training happens for first digit. I don't know what's the problem. I'm thinking this is related to batch training that after one time training, second digit can't because network converged. but I cant how to solve it. I tested with multi layer perceptron and I get the same behaviour. NOTE: every time i choose one digit and load a lot of them and start training, and for others digits i restart every thing except weight matrix(w0) this is my code: 1-importing libraries: import os, struct from array import array as pyarray from numpy import append, array, int8, uint8, zeros import numpy as np from IPython.display import Image import matplotlib.pyplot as plt from IPython import display from scipy.special import expit from scipy.misc import imresize from IPython.core.page import page from IPython.core.formatters import format_display_data np.set_printoptions(threshold=np.nan) np.set_printoptions(suppress=True) 2- Sigmoid function: def sigmoid(x, deriv=False): if(deriv==True): return x*(1-x) return expit(x) 3- Initializing weights np.random.seed(1) w0 = 2*np.random.random((784,10))-1 4- Reading MNIST dataset dataset="training" path="." if dataset == "training": fname_img = os.path.join(path, 'train-images-idx3-ubyte') fname_lbl = os.path.join(path, 'train-labels-idx1-ubyte') elif dataset == "testing": fname_img = os.path.join(path, 't10k-images-idx3-ubyte') fname_lbl = os.path.join(path, 't10k-labels-idx1-ubyte') else: raise ValueError("dataset must be 'testing' or 'training'") flbl = open(fname_lbl, 'rb') magic_nr, size = struct.unpack(">II", flbl.read(8)) lbl = pyarray("b", flbl.read()) flbl.close() fimg = open(fname_img, 'rb') magic_nr, size, rows, cols = struct.unpack(">IIII", fimg.read(16)) img = pyarray("B", fimg.read()) fimg.close() 5- Choosing a number number = 4 digits=[number] ind = [ k for k in range(size) if lbl[k] in digits ] N = len(ind) images = zeros((N, rows, cols), dtype=uint8) labels = zeros((N, 1), dtype=int8) for i in range(len(ind)): images[i] = array(img[ ind[i]*rows*cols : (ind[i]+1)*rows*cols ]).reshape((rows, cols)) labels[i] = lbl[ind[i]] 6- Converting each digit to a vector and converting matrix cells to binary: p = np.reshape(images,(len(images),784)) p[p > 0] = 1 7- Target matrix(each column for a digit) t = np.zeros((len(images), 10),dtype=float) t[:,number] = 1 8- Training(Gradient descent) for iter in xrange(600): predict = sigmoid(np.dot(p,w0)) e0 = predict - t delta0 = e0 * sigmoid(predict,True) w0 -= 0.01*np.dot(p.T,delta0) 9- testing test_predict = sigmoid(np.dot(p[102],w0)) print test_predict
1
1
0
1
0
0
I have a keyword "grand master" and I am searching for the keyword in the huge text. I need to extract 5 before words and 5 after words of the keyword (based on the position it might go to the next/before sentence also), and this keyword appears multiple times in huge text. As a trail , first i tried to find the position of the keyword in the text, usingtext.find(), and found the keywords at 4 different positions >>positions >>[125, 567,34445, 98885445] So tried to split the text based on spaces and taking first 5 words, text[positions[i]:].split([len(keyword.split()):len(keyword.split())+5] But how to extract the 5 words before that keyword?
1
1
0
0
0
0
I am trying to calculate text similarity between sentences. I have standardized medical services list containing text of service ( for e.g. consultation of neurologist). Every time hospital/clinic comes with their own service list so I need to map hospital's service list with standardized service list. I calculate TF-IDF cosine similarity between hospital's service with standardized service list using skip-gram tokens. I have been doing this for long time so I also have correct mapping of services of some 15 hospitals. By 'correct mapping', I mean medical experts from my organization provided correct mapping of services which are wrongly labelled or mapped using tf-idf cosine similarity algorithm. I want to use 'correct mapping' as text classification problem but no. of labels in this case is more than 10K. Is there a way to perform 'Supervised text similarity'? I tried word2vec algorithm but it does not incorporate supervised element (i.e. target variable (correct mapping of previous results)). Currently I am using R. I am open for Python as well. See the example of my datasets below ( consider A as 'standardized service list', B as 'hospital's service list', C as 'correct mapping') . A <- data.frame(name= c("Patient had X-ray right leg arteries.", "Subject was administered Rgraphy left shoulder", "Exam consisted of x-ray leg arteries", "Patient administered x-ray leg with 20km distance."), row.names = paste0("A", 1:4), stringsAsFactors = FALSE) B <- data.frame(name= c(B = "Patient had X-ray left leg arteries", "Rgraphy right shoulder given to patient", "X-ray left shoulder revealed nothing sinister", "Rgraphy right leg arteries tested"), row.names = paste0("A", 1:4), stringsAsFactors = FALSE) C <- data.frame(name= c("Patient had X-ray right leg arteries.", "Subject was administered Rgraphy left shoulder", "Exam consisted of x-ray leg arteries", "Patient administered x-ray leg with 20km distance."), mapping = c("Radiography right leg artery.", "Radiography left shoulder", "Radiography leg arteries", "Radiography leg with more than 10km distance."), row.names = paste0("A", 1:4), stringsAsFactors = FALSE)
1
1
0
0
0
0
I'm running Python-3.x on a virtualenv, trying to process text with nltk. I saw this post What are ngram counts... and the most upvoted answer has a bit of code using the count() method. but when I copy/paste it into mine: import nltk from nltk import bigrams from nltk import trigrams text="""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare tempor lacus, quis pellentesque diam tempus vitae. Morbi justo mauris, congue sit amet imperdiet ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare tempor lacus, quis pellentesque diam""" tokens = nltk.word_tokenize(text) tokens = [token.lower() for token in tokens if len(token) > 1] bi_tokens = bigrams(tokens) tri_tokens = trigrams(tokens) print [(item, tri_tokens.count(item)) for item in sorted(set(tri_tokens))] I receive this message: AttributeError: 'generator' object has no attribute 'count' I see this other post on a monkeypatch for a count method but feel like that's somehow not related. Any idea what I might be doing wrong?
1
1
0
0
0
0
I'm looking for a way to automatically determine the natural language used by a website page, given its URL. In Python, a function like: def LanguageUsed (url): #stuff Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...) Summary of Results: I have a reasonable solution working in Python using code from the PyPi for oice.langdet. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license. For a more general solution using Trigrams in Python as others have suggested, see this Python Cookbook Recipe from ActiveState. The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.
1
1
0
0
0
0
Since I am new to deep learning this question may be funny to you. but I couldn't visualize it in the mind. That's why I am asking about it. I am giving a sentence as the vector to the LSTM, Think I have a sentence contains 10 words. Then I change those sentences to the vectors and giving it to the LSTM. The length of the LSTM cells should be 10. But in most of the tutorials, I have seen they have added 128 hidden states. I couldn't understand and visualize it. What's that the word means by LSTM layer with "128-dimensional hidden state" for example: X = LSTM(128, return_sequences=True)(embeddings) The summery of this looks lstm_1 (LSTM) (None, 10, 128) 91648 Here It looks like 10 LSTM cells are added but why are that 128 hidden states there? Hope you may understand what I am expecting.
1
1
0
0
0
0
I have a few lines of text and want to remove any word with special characters or a fixed given string in them (in python). Example: in_lines = ['this is go:od', 'that example is bad', 'amp is a word'] # remove any word with {'amp', ':'} out_lines = ['this is', 'that is bad', 'is a word'] I know how to remove words from a list that is given but cannot remove words with special characters or few letters being present. Please let me know and I'll add more information. This is what I have for removing selected words: def remove_stop_words(lines): stop_words = ['am', 'is', 'are'] results = [] for text in lines: tmp = text.split(' ') for stop_word in stop_words: for x in range(0, len(tmp)): if tmp[x] == stop_word: tmp[x] = '' results.append(" ".join(tmp)) return results out_lines = remove_stop_words(in_lines)
1
1
0
0
0
0
I am finding the optimal value of hyperparameter alpha for my Multinpmial Naive Bayes model which uses cross validation and neg_log_loss as metric. I wrote thie code: alphas = list(range(1, 500)) #perform k fold cross validation for different metrics def cross_val(metric): MSE = [] cv_scores = [] training_scores = [] for alpha in alphas: naive_bayes = MultinomialNB(alpha=alpha) scores = cross_val_score(naive_bayes, x_train_counts, y_train, cv=20, scoring='neg_log_loss') #score() returns the mean accuracy on the given test data and labels scores_training = naive_bayes.fit(x_train_counts, y_train).score(x_train_counts, y_train) cv_scores.append(scores.mean()) training_scores.append(scores_training) #changing to misclassification error MSE = [1 - x for x in cv_scores] #determining best alpha optimal_alpha = alphas[MSE.index(min(MSE))] print(' The optimal value of alpha for %s is %f' % (metric, optimal_alpha)) return optimal_alpha optimal_alpha = cross_val('neg_log_loss') The above code was initially working. Now it's throwing following error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-43-facbaa3537ca> in <module>() ----> 1 optimal_alpha = cross_val('neg_log_loss') 2 prediction(optimal_alpha, 'neg_log_loss') <ipython-input-41-ff0a9191d45c> in cross_val(metric) 13 for alpha in alphas: 14 naive_bayes = MultinomialNB(alpha=alpha) ---> 15 scores = cross_val_score(naive_bayes, x_train_counts, y_train, cv=20, scoring='neg_log_loss') 16 17 #score() returns the mean accuracy on the given test data and labels ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/cross_validation.py in cross_val_score(estimator, X, y, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch) 1579 train, test, verbose, None, 1580 fit_params) -> 1581 for train, test in cv) 1582 return np.array(scores)[:, 0] 1583 ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable) 777 # was dispatched. In particular this covers the edge 778 # case of Parallel used with an exhausted iterator. --> 779 while self.dispatch_one_batch(iterator): 780 self._iterating = True 781 else: ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in dispatch_one_batch(self, iterator) 623 return False 624 else: --> 625 self._dispatch(tasks) 626 return True 627 ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in _dispatch(self, batch) 586 dispatch_timestamp = time.time() 587 cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self) --> 588 job = self._backend.apply_async(batch, callback=cb) 589 self._jobs.append(job) 590 ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py in apply_async(self, func, callback) 109 def apply_async(self, func, callback=None): 110 """Schedule a func to be run""" --> 111 result = ImmediateResult(func) 112 if callback: 113 callback(result) ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py in __init__(self, batch) 330 # Don't delay the application, to avoid keeping the input 331 # arguments in memory --> 332 self.results = batch() 333 334 def get(self): ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self) 129 130 def __call__(self): --> 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] 132 133 def __len__(self): ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in <listcomp>(.0) 129 130 def __call__(self): --> 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] 132 133 def __len__(self): ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/cross_validation.py in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, error_score) 1692 1693 else: -> 1694 test_score = _score(estimator, X_test, y_test, scorer) 1695 if return_train_score: 1696 train_score = _score(estimator, X_train, y_train, scorer) ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/cross_validation.py in _score(estimator, X_test, y_test, scorer) 1749 score = scorer(estimator, X_test) 1750 else: -> 1751 score = scorer(estimator, X_test, y_test) 1752 if hasattr(score, 'item'): 1753 try: ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/metrics/scorer.py in __call__(self, clf, X, y, sample_weight) 142 **self._kwargs) 143 else: --> 144 return self._sign * self._score_func(y, y_pred, **self._kwargs) 145 146 def _factory_args(self): ~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/metrics/classification.py in log_loss(y_true, y_pred, eps, normalize, sample_weight, labels) 1684 "y_true: {2}".format(transformed_labels.shape[1], 1685 y_pred.shape[1], -> 1686 lb.classes_)) 1687 else: 1688 raise ValueError('The number of classes in labels is different ' ValueError: y_true and y_pred contain different number of classes 26, 27. Please provide the true labels explicitly through the labels argument. Classes found in y_true: [ 2 4 5 6 7 8 9 10 11 12 14 15 16 17 19 21 22 23 24 27 29 30 31 32 33 35] This code worked few times initially. Suddenly, it stopped working. How can I make it work?
1
1
0
1
0
0
I've been trying to write a code for sentences splitting. And it worked very well in English and other left-to-right Latin-lettered languages. When I tried to do the same with Arabic, the text came up totally disconnected, like each letter individually. I'm not sure what the problem is. My input text: عندما يريد العالم أن يتكلّم، فهو يتحدّث بلغة يونيكود. سجّل الآن لحضور المؤتمر الدولي العاشر ليونيكود، الذي سيعقد في آذار بمدينة مَايِنْتْس، ألمانيا. و سيجمع المؤتمر بين خبراء من كافة قطاعات الصناعة على الشبكة العالمية انترنيت ويونيكود، حيث ستتم، على الصعيدين الدولي والمحلي على حد سواء مناقشة سبل استخدام يونكود في النظم القائمة وفيما يخص التطبيقات الحاسوبية، الخطوط، تصميم النصوص والحوسبة متعددة اللغات. My code: # -*- coding: utf-8 -*- import nltk from nltk import sent_tokenize import codecs import csv sentences = codecs.open('SampleArabic.txt', 'r', 'utf-8-sig').read() def split_sentences(sentences): with codecs.open('Output_AR.txt', 'w', encoding='utf-8') as writer: newcount = 0 for sent in sent_tokenize(sentences): print(sent.encode('utf-8')) wr = csv.writer(writer,delimiter=' ') wr.writerow(str(sent)) newcount = sentences.count(sentences)+newcount print(newcount) pass split_sentences(sentences) My first issue is that the console prints the text in code: b'\xd8\xb9\xd9\x86\xd8\xaf\xd9\x85\xd8\xa7 \xd9\x8a\xd8\xb1\xd9\x8a\xd8\xaf \xd8\xa7\xd9\x84\xd8\xb9\xd8\xa7\xd9\x84\xd9\x85 \xd8\xa3\xd9\x86 \xd9\x8a\xd8\xaa\xd9\x83\xd9\x84\xd9\x91\xd9\x85 \xe2\x80\xac \xd8\x8c \xd9\x81\xd9\x87\xd9\x88 \xd9\x8a\xd8\xaa\xd8\xad\xd8\xaf\xd9\x91\xd8\xab \xd8\xa8\xd9\x84\xd8\xba\xd8\xa9 \xd9\x8a\xd9\x88\xd9\x86\xd9\x8a\xd9\x83\xd9\x88\xd8\xaf.' b'\xd8\xb3\xd8\xac\xd9\x91\xd9\x84 \xd8\xa7\xd9\x84\xd8\xa2\xd9\x86 \xd9\x84\xd8\xad\xd8\xb6\xd9\x88\xd8\xb1 \xd8\xa7\xd9\x84\xd9\x85\xd8\xa4\xd8\xaa\xd9\x85\xd8\xb1 \xd8\xa7\xd9\x84\xd8\xaf\xd9\x88\xd9\x84\xd9\x8a \xd8\xa7\xd9\x84\xd8\xb9\xd8\xa7\xd8\xb4\xd8\xb1 \xd9\x84\xd9\x8a\xd9\x88\xd9\x86\xd9\x8a\xd9\x83\xd9\x88\xd8\xaf\xd8\x8c \xd8\xa7\xd9\x84\xd8\xb0\xd9\x8a \xd8\xb3\xd9\x8a\xd8\xb9\xd9\x82\xd8\xaf \xd9\x81\xd9\x8a \xd8\xa2\xd8\xb0\xd8\xa7\xd8\xb1 \xd8\xa8\xd9\x85\xd8\xaf\xd9\x8a\xd9\x86\xd8\xa9 \xd9\x85\xd9\x8e\xd8\xa7\xd9\x8a\xd9\x90\xd9\x86\xd9\x92\xd8\xaa\xd9\x92\xd8\xb3\xd8\x8c \xd8\xa3\xd9\x84\xd9\x85\xd8\xa7\xd9\x86\xd9\x8a\xd8\xa7.' b'\xd9\x88 \xd8\xb3\xd9\x8a\xd8\xac\xd9\x85\xd8\xb9 \xd8\xa7\xd9\x84\xd9\x85\xd8\xa4\xd8\xaa\xd9\x85\xd8\xb1 \xd8\xa8\xd9\x8a\xd9\x86 \xd8\xae\xd8\xa8\xd8\xb1\xd8\xa7\xd8\xa1 \xd9\x85\xd9\x86 \xd9\x83\xd8\xa7\xd9\x81\xd8\xa9 \xd9\x82\xd8\xb7\xd8\xa7\xd8\xb9\xd8\xa7\xd8\xaa \xd8\xa7\xd9\x84\xd8\xb5\xd9\x86\xd8\xa7\xd8\xb9\xd8\xa9 \xd8\xb9\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd8\xb4\xd8\xa8\xd9\x83\xd8\xa9 \xd8\xa7\xd9\x84\xd8\xb9\xd8\xa7\xd9\x84\xd9\x85\xd9\x8a\xd8\xa9 \xd8\xa7\xd9\x86\xd8\xaa\xd8\xb1\xd9\x86\xd9\x8a\xd8\xaa \xd9\x88\xd9\x8a\xd9\x88\xd9\x86\xd9\x8a\xd9\x83\xd9\x88\xd8\xaf\xd8\x8c \xd8\xad\xd9\x8a\xd8\xab \xd8\xb3\xd8\xaa\xd8\xaa\xd9\x85\xd8\x8c \xd8\xb9\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd8\xb5\xd8\xb9\xd9\x8a\xd8\xaf\xd9\x8a\xd9\x86 \xd8\xa7\xd9\x84\xd8\xaf\xd9\x88\xd9\x84\xd9\x8a \xd9\x88\xd8\xa7\xd9\x84\xd9\x85\xd8\xad\xd9\x84\xd9\x8a \xd8\xb9\xd9\x84\xd9\x89 \xd8\xad\xd8\xaf \xd8\xb3\xd9\x88\xd8\xa7\xd8\xa1 \xd9\x85\xd9\x86\xd8\xa7\xd9\x82\xd8\xb4\xd8\xa9 \xd8\xb3\xd8\xa8\xd9\x84 \xd8\xa7\xd8\xb3\xd8\xaa\xd8\xae\xd8\xaf\xd8\xa7\xd9\x85 \xd9\x8a\xd9\x88\xd9\x86\xd9\x83\xd9\x88\xd8\xaf \xd9\x81\xd9\x8a \xd8\xa7\xd9\x84\xd9\x86\xd8\xb8\xd9\x85 \xd8\xa7\xd9\x84\xd9\x82\xd8\xa7\xd8\xa6\xd9\x85\xd8\xa9 \xd9\x88\xd9\x81\xd9\x8a\xd9\x85\xd8\xa7 \xd9\x8a\xd8\xae\xd8\xb5 \xd8\xa7\xd9\x84\xd8\xaa\xd8\xb7\xd8\xa8\xd9\x8a\xd9\x82\xd8\xa7\xd8\xaa \xd8\xa7\xd9\x84\xd8\xad\xd8\xa7\xd8\xb3\xd9\x88\xd8\xa8\xd9\x8a\xd8\xa9\xd8\x8c \xd8\xa7\xd9\x84\xd8\xae\xd8\xb7\xd9\x88\xd8\xb7\xd8\x8c \xd8\xaa\xd8\xb5\xd9\x85\xd9\x8a\xd9\x85 \xd8\xa7\xd9\x84\xd9\x86\xd8\xb5\xd9\x88\xd8\xb5 \xd9\x88\xd8\xa7\xd9\x84\xd8\xad\xd9\x88\xd8\xb3\xd8\xa8\xd8\xa9 \xd9\x85\xd8\xaa\xd8\xb9\xd8\xaf\xd8\xaf\xd8\xa9 \xd8\xa7\xd9\x84\xd9\x84\xd8\xba\xd8\xa7\xd8\xaa.' 3 But I think it is the minor problem. The main issue, as I mentioned before, is that the output text file has the text totally disconnected. In Notepad it looks like this: https://i.stack.imgur.com/Fhmqh.png And in NotePad++ it looks like this: https://i.stack.imgur.com/gcA6z.png I'm using Python 3.4. And this is only my 2nd attempt with Python. So, I might need some extra details.
1
1
0
0
0
0
I was able to train a language model using the tensorflow tutorials , the models are saved as checkpoint files as per the code given here. save_path = saver.save(sess, "/tmp/model.epoch.%03d.ckpt" % (i + 1)) Now I need to restore the checkpoint and use it in the following code: def run_epoch(session, m, data, eval_op, verbose=False): """Runs the model on the given data.""" epoch_size = ((len(data) // m.batch_size) - 1) // m.num_steps start_time = time.time() costs = 0.0 iters = 0 state = m.initial_state.eval() for step, (x, y) in enumerate(reader.ptb_iterator(data, m.batch_size, m.num_steps)): cost, state, _ = session.run([m.cost, m.final_state, eval_op], {m.input_data: x, m.targets: y, m.initial_state: state}) costs += cost iters += m.num_steps if verbose and step % (epoch_size // 10) == 10: print("%.3f perplexity: %.3f speed: %.0f wps" % (step * 1.0 / epoch_size, np.exp(costs / iters), iters * m.batch_size / (time.time() - start_time))) return np.exp(costs / iters) I cannot find any way of encoding the test sentences and getting sentence probability output from the trained checkpoint model. The tutorials mention following code: probabilities = tf.nn.softmax(logits) but that it is for training and I cannot figure out how do I get the actual probabilities. I should Ideally get something like : >>getprob('this is a temp sentence') >>0.322
1
1
0
1
0
0
Given sentences like: 'the people are all watching and listening to the bikers on the corner of the road' 'woman on snow skis being pulled by dogs.' (Actually, the sentences I want to process are captions in MSCOCO datatset) I want to extract the scene/place words in the sentence. For example, 'road', 'snow' here are the scene/place words. I have tried NER in stanfordcorenlp, but it can only extract the location name, not a scene word. Could anyone give me a clue about how to extract such words? Thanks.
1
1
0
0
0
0
I have to do a averaging of 3d Tensor, where first dimension represents batch_size , second dimension reporesents max_length of sentence ( time axis ) in the batch and last dimension represents the embedding dimension. Those who are familiar with lstm, it is obtained by tf.nn.emebedding_lookup For example: Assume I have 3 sentences [ [i, love, you,], [i, don't, love, you,], [i, always, love, you, so, much ]] Here batch_size = 3, max_length = 6 (3rd sentence ) and assume embedding dimension = 100. Normally, we will pad the first 2 sentences to match the max_length. Now, I need to average the word embeddings of each word. But, if I am using tf.reduce_sum, it will consider those padded vectors into consideration for the first two sentences, which is wrong. Is there an efficient way to do this in tensorflow.
1
1
0
0
0
0
I am new to the Google Natural Language Processing Library...and trying to get entities from a text file locally but keeps getting error. I've tried even the sample code from Google but the error is the same. Here's my code: import six from google.cloud import language from google.cloud.language import enums from google.cloud.language import types def entities_text(text): """Detects entities in the text.""" client = language.LanguageServiceClient(credentials='cred.json') if isinstance(text, six.binary_type): text = text.decode('utf-8') # Instantiates a plain text document. document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) # Detects entities in the document. You can also analyze HTML with: # document.type == enums.Document.Type.HTML entities = client.analyze_entities(document).entities # entity types from enums.Entity.Type entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION', 'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER') for entity in entities: print('=' * 20) print(u'{:<16}: {}'.format('name', entity.name)) print(u'{:<16}: {}'.format('type', entity_type[entity.type])) print(u'{:<16}: {}'.format('metadata', entity.metadata)) print(u'{:<16}: {}'.format('salience', entity.salience)) print(u'{:<16}: {}'.format('wikipedia_url', entity.metadata.get('wikipedia_url', '-'))) if __name__ == "__main__": with open('test.txt', 'r') as text: text = text.read() ent = entities_text(text) print(ent) Here's the stacktrace: AuthMetadataPluginCallback " <google.auth.transport.grpc.AuthMetadataPlugin object at 0x7f6973b4a668>" raised exception! Traceback (most recent call last): File "/home/user/Documents/CODE/venv/lib/python3.6/site- packages/grpc/_plugin_wrapping.py", line 79, in __call__ callback_state, callback)) File "/home/user/Documents/CODE/venv/lib/python3.6/site- packages/google/auth/transport/grpc.py", line 77, in __call__ callback(self._get_authorization_headers(context), None) File "/home/user/Documents/CODE/venv/lib/python3.6/site- packages/google/auth/transport/grpc.py", line 61, in _get_authorization_headers self._credentials.before_request( AttributeError: 'str' object has no attribute 'before_request' How do I get it to return the entities please?
1
1
0
1
0
0
I have a folder of txt files and also a csv file with additional data like categories a particular txt document belongs to and the original source file (pdf) path. The Txt file name is used as key into the CSV file. I have created a basic nltk corpus but I would like to know if that's the best way of structuring my data given I want to carry out a range of NLP tasks like NER on the corpus and eventually identify the entities which occur in each category and be able to link back to the source pdf files so each entity can be seen in context. Most NLP examples (find NERs) go from corpus to python lists of entities but doesn't that mean I will loose the association back to the txt file which contained the entities and all the other associated data? Categorical corpus appears to help with keeping the category data but my question is What is the best way to structure and work with my corpus that avoids having to roundtrip between - process corpus to identify interesting information outputted to list - search corpus again to get files which contains the interested element from the list - search CSV (data frame) by file id to get the rest of the metadata
1
1
0
0
0
0
I want to remove nonsense words in my dataset. I tried which I saw StackOverflow something like this: import nltk words = set(nltk.corpus.words.words()) sent = "Io andiamo to the beach with my amico." " ".join(w for w in nltk.wordpunct_tokenize(sent) \ if w.lower() in words or not w.isalpha()) But now since I have a dataframe how do i iterate it over the whole column. I tried something like this: import nltk words = set(nltk.corpus.words.words()) sent = df['Chats'] df['Chats'] = df['Chats'].apply(lambda w:" ".join(w for w in nltk.wordpunct_tokenize(sent) \ if w.lower() in words or not w.isalpha())) But I am getting an error TypeError: expected string or bytes-like object
1
1
0
1
0
0
I am trying to make a program that compares soccer team names from two different sites through Python. My problem is that the names are not the exactly same. For example on the first site a name is: Liverpool Football Club On the second site it's: Liverpool FC I've been trying to use the module: fuzzywuzzy and it's fuzz.ratio function but it doesn't really do the trick. If I put the fuzz.ratio at 30, it will match wrongly, and if I put fuzz.ratio too high it wont match rightly. Is there a smarter way to match names in Python?
1
1
0
0
0
0
I want to make AI bot which can understand only 4 words "Up", "Down", "Left", "Right". as my friend make a python script which executes some task by the voice like to open youtube just say "Youtube" and Chrome browser will open with youtube.com URL. But the system was slow as they were using google assistant/ai to process the voice which makes me feel impatient. Then I got an idea what if an AI system offline which Understand only a few words and we can get some desired result and will be super fast. for example:- I have a remote control car I want to make voice-activated as when I say "Up" car should move forward, similarly for "Down" -> Backward, "Left" -> Left and "Right" -> Right & "{Any other voice}" -> blink the led to tell that the system didn't understand so, please someone help me. how should i start? how should i train the AI Bot? what should be my requirements? and other thing that i should know. Thank You.
1
1
0
1
0
0
I have a training text file with the following format (pos, word, tag): 1 i PRP 2 'd MD 3 like VB 4 to TO 5 go VB 6 . . 1 i PRP I am trying to build a dictionary so that when I input a new corpus with the following format (pos, word): 1 who 2 knows 3 what 4 will 5 happen 6 . I will be able to tag these from the dictionary I've built with the training data. the method I'm using is a counter in default dictionary to find the most common tag for a word. From my counter, I'm getting print results like this: i PRP 7905 'd MD 1262 like VB 2706 like VBP 201 like UH 95 like IN 112 to TO 4822 to IN 922 So for the word "like", the tag with the highest counts is 'VB' at 2706. I want to my dictionary to take the tag with the highest count and attach it to my word so that if I put a test data set with just the (pos, word), it will return that tag. Here's my code so far: file=open("/Users/Desktop/training.txt").read().split(' ') from collections import Counter, defaultdict word_tag_counts = defaultdict(Counter) for row in file: if not row.strip(): continue pos, word, tag = row.split() word_tag_counts[word.lower()][tag] += 1 stats = word_tag_counts max(stats, key=stats.get) with open('/Users/Desktop/training.txt','r') as file: for line in file.readlines(): column = line.split('\t') with open('/Users/Desktop/output.txt','w') as file: for tag, num in d.items(): file.write("\t".join([column[0], column[1], tag])+" ") I'm getting the error: TypeError: '>' not supported between instances of 'Counter' and 'Counter' my output goal is in the same format as the original training file (pos pulled from original txt file, word from original txt file, tag from my dictionary): Not sure what I can, i tried using lambda as well but it's not working. Anything will help. Thanks.
1
1
0
0
0
0
I want to remove all the digits in my dataframe. I did something like this: for row in df['msg'].iteritems(): df['msg'][row] = re.sub(r"\d"," ",df['msg'][row]) but got an error <ipython-input-18-79f64a70b2a4> in <module>() 4 import re 5 for row in df['msg'].iteritems(): ----> 6 df['msg'][row] = re.sub(r"\d"," ",df['msg'][row]) 7 print(df['msg']) C:\Users\Pratik\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key) 599 key = com._apply_if_callable(key, self) 600 try: --> 601 result = self.index.get_value(self, key) 602 603 if not is_scalar(result): C:\Users\Pratik\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 2426 try: 2427 return self._engine.get_value(s, k, -> 2428 tz=getattr(series.dtype, 'tz', None))
1
1
0
0
0
0
[TF 1.8] I'm trying to build a seq2seq model for a toy chatbot to learn about tensorflow and deep learning. I was able to train and run the model with sampled softmax and beam search but then I try to apply tf.contrib.seq2seq.LuongAttention using tf.contrib.seq2seq.AttentionWrapper I get the following error while building the graph: ValueError: Dimensions must be equal, but are 384 and 256 for 'rnn/while/rnn/multi_rnn_cell/cell_0/basic_lstm_cell/MatMul_2' (op: 'MatMul') with input shapes: [64,384], [256,512]. This is my model: class ChatBotModel: def __init__(self, inferring=False, batch_size=1, use_sample_sofmax=True): """forward_only: if set, we do not construct the backward pass in the model. """ print('Initialize new model') self.inferring = inferring self.batch_size = batch_size self.use_sample_sofmax = use_sample_sofmax def build_graph(self): # INPUTS self.X = tf.placeholder(tf.int32, [None, None]) self.Y = tf.placeholder(tf.int32, [None, None]) self.X_seq_len = tf.placeholder(tf.int32, [None]) self.Y_seq_len = tf.placeholder(tf.int32, [None]) self.gl_step = tf.Variable( 0, dtype=tf.int32, trainable=False, name='global_step') single_cell = tf.nn.rnn_cell.BasicLSTMCell(128) keep_prob = tf.cond(tf.convert_to_tensor(self.inferring, tf.bool), lambda: tf.constant( 1.0), lambda: tf.constant(0.8)) single_cell = tf.contrib.rnn.DropoutWrapper( single_cell, output_keep_prob=keep_prob) encoder_cell = tf.contrib.rnn.MultiRNNCell([single_cell for _ in range(2)]) # ENCODER encoder_out, encoder_state = tf.nn.dynamic_rnn( cell = encoder_cell, inputs = tf.contrib.layers.embed_sequence(self.X, 10000, 128), sequence_length = self.X_seq_len, dtype = tf.float32) # encoder_state is ((cell0_c, cell0_h), (cell1_c, cell1_h)) # DECODER INPUTS after_slice = tf.strided_slice(self.Y, [0, 0], [self.batch_size, -1], [1, 1]) decoder_inputs = tf.concat( [tf.fill([self.batch_size, 1], 2), after_slice], 1) # ATTENTION attention_mechanism = tf.contrib.seq2seq.LuongAttention( num_units = 128, memory = encoder_out, memory_sequence_length = self.X_seq_len) # DECODER COMPONENTS Y_vocab_size = 10000 decoder_cell = tf.contrib.rnn.MultiRNNCell([single_cell for _ in range(2)]) decoder_cell = tf.contrib.seq2seq.AttentionWrapper( cell = decoder_cell, attention_mechanism = attention_mechanism, attention_layer_size=128) decoder_embedding = tf.Variable(tf.random_uniform([Y_vocab_size, 128], -1.0, 1.0)) projection_layer = CustomDense(Y_vocab_size) if self.use_sample_sofmax: softmax_weight = projection_layer.kernel softmax_biases = projection_layer.bias if not self.inferring: # TRAINING DECODER training_helper = tf.contrib.seq2seq.TrainingHelper( inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_inputs), sequence_length = self.Y_seq_len, time_major = False) decoder_initial_state = decoder_cell.zero_state(self.batch_size, dtype=tf.float32).clone( cell_state=encoder_state) training_decoder = tf.contrib.seq2seq.BasicDecoder( cell = decoder_cell, helper = training_helper, initial_state = decoder_initial_state, output_layer = projection_layer ) training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode( decoder = training_decoder, impute_finished = True, maximum_iterations = tf.reduce_max(self.Y_seq_len)) training_logits = training_decoder_output.rnn_output # LOSS softmax_loss_function = None if self.use_sample_sofmax: def sampled_loss(labels, logits): labels = tf.reshape(labels, [-1, 1]) return tf.nn.sampled_softmax_loss(weights=softmax_weight, biases=softmax_biases, labels=labels, inputs=logits, num_sampled=64, num_classes=10000) softmax_loss_function = sampled_loss masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32) self.loss = tf.contrib.seq2seq.sequence_loss(logits = training_logits, targets = self.Y, weights = masks, softmax_loss_function=softmax_loss_function) # BACKWARD params = tf.trainable_variables() gradients = tf.gradients(self.loss, params) clipped_gradients, _ = tf.clip_by_global_norm(gradients, 5.0) self.train_op = tf.train.AdamOptimizer().apply_gradients(zip(clipped_gradients, params), global_step=self.gl_step) else: encoder_states = [] for i in range(2): if isinstance(encoder_state[i],tf.contrib.rnn.LSTMStateTuple): encoder_state_c = tf.contrib.seq2seq.tile_batch(encoder_state[i].c, multiplier=2) encoder_state_h = tf.contrib.seq2seq.tile_batch(encoder_state[i].h, multiplier=2) encoder_state = tf.contrib.rnn.LSTMStateTuple(c=encoder_state_c, h=encoder_state_h) encoder_states.append(encoder_state) encoder_states = tuple(encoder_states) predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder( cell = decoder_cell, embedding = decoder_embedding, start_tokens = tf.tile(tf.constant([2], dtype=tf.int32), [self.batch_size]), end_token = 3, initial_state = decoder_initial_state, beam_width = 2, output_layer = projection_layer, length_penalty_weight = 0.0) predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode( decoder = predicting_decoder, impute_finished = False, maximum_iterations = 4 * tf.reduce_max(self.Y_seq_len)) self.predicting_logits = predicting_decoder_output.predicted_ids Tracing back a few lines of log and I saw that the error occurs here: /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/rnn_cell_impl.py in call(self, inputs, state) 636 637 gate_inputs = math_ops.matmul( --> 638 array_ops.concat([inputs, h], 1), self._kernel) 639 gate_inputs = nn_ops.bias_add(gate_inputs, self._bias) I have checked the 'h' tensor of the LSTM cell and it has the shape of [batch_size, 128] so my guess is that the attention output from the previous decoding step is concatenated with the current encoder's input make the 'inputs' has the shape of [batch_size, 256] then it is concatenated with 'h' tensor to form a [batch_size, 384] tensor causing this error. My question is: Isn't attention output supposed to be concatenated with the next decoder's input or I miss understanding anything? And how to fix this error.
1
1
0
0
0
0
I am new to Python and just started using it with NLP, I need to write a regular expression based named entity recognition module. Anyone provide me with helpful links or examples will be appreciated.
1
1
0
0
0
0
I'm trying to train a simple model with Keras and python. The text is preprocessed perfectly. But when I try to fit it I get the following error: File "main.py", line 47, in <module> model.fit(x_train, y_train, batch_size=32, epochs=3) File "/home/shamildacoder/.local/lib/python3.6/site-packages/keras/engine/training.py", line 952, in fit batch_size=batch_size) File "/home/shamildacoder/.local/lib/python3.6/site-packages/keras/engine/training.py", line 789, in _standardize_user_data exception_prefix='target') File "/home/shamildacoder/.local/lib/python3.6/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data str(data_shape)) ValueError: Error when checking target: expected dense_2 to have shape (121885,) but got array with shape (1000,) But print(x_train.shape) and print(y_train.shape) both return (121885, 1000). I don't see any reason. Code: https://pastebin.com/afnzBf6B from keras.preprocessing.text import Tokenizer from keras.layers import Dense from keras.models import Sequential data = open('movie_lines.txt', encoding='ISO-8859-1') lines = [line for line in data] filtered_lines = [] for line in lines: sentence = line.split('+++$+++')[4].strip(' ') filtered_lines.append(sentence) train_size = int(len(filtered_lines) * .8) train_portion = filtered_lines[:train_size] test_portion = filtered_lines[train_size:] x_lines = train_portion[::2] y_lines = train_portion[1::2] x_test = test_portion[::2] y_test = test_portion[1::2] vocab_size = 1000 print('Prepared data') def prepare_text(text): tokenizer = Tokenizer(num_words=vocab_size) tokenizer.fit_on_texts(text) matrix = tokenizer.texts_to_matrix(text) return matrix x_train = prepare_text(x_lines) print('matrixed x') y_train = prepare_text(y_lines) print('matrixed y') print(f'X shape: {x_train.shape}') print(f'Y shape: {y_train.shape}') model = Sequential() model.add(Dense(512, input_shape=(vocab_size,), activation='relu')) model.add(Dense(len(y_lines), activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy',] ) print('Created and compiled model') model.fit(x_train, y_train, epochs=3) score = model.evaluate(x_test, y_test, batch_size=32, epochs=3) print('Test Score:'+score[0]) print('Test Accuracy:'+score[1])
1
1
0
1
0
0
So, I was given a use case. The use case is to find PHI in multiple text files using regular expressions and python at once. So basically, Open all text files in your directory and then filter the content of each file with regular expressions to see which file has PHI in them. Any ideas?
1
1
0
0
0
0
I have a csv with msg column and it has the following text muchloveandhugs dudeseriously onemorepersonforthewin havefreebiewoohoothankgod thisismybestcategory yupbabe didfreebee heykidforget hecomplainsaboutit I know that nltk.corpus.words has a bunch of sensible words. My problem is how do I iterate it over the df[‘msg’] column so that I can get words such as df[‘msg’] much love and hugs dude seriously one more person for the win
1
1
0
0
0
0
I'm using NLTK to stem words from text, and doing some basic analytics with those words. However, for display purposed, I want to convert those stems back to the "root" word (but not back to the same form or conjugation it started with). For example: >>> import nltk >>> from nltk.stem import SnowballStemmer >>> sn = SnowballStemmer("english") >>> sn.stem("happiness") u'happi' >>> sn.stem("happy") u'happi' # What I want to do: >>> some_unstem_function("happi") u'happy' Is there a function or method for doing this?
1
1
0
0
0
0
With this Gensim example in github, https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-wikipedia.ipynb it provides examples at the end to find simalarities with phrases or keywords, like 'lady gaga' or 'machine learning'. However am looking to find similarity with actual document in plain text file, could this be done? and how can I do it? suppose text file is located on my local laptop in txt format.
1
1
0
0
0
0
I'm training myself with some text data trying to do some simple actions on it. At first the word "Data" was with a frequency of 7, but then i found on the same text more words related to it "data", so i lowered all the text in order to gain the missing words. the final frequency for "data" is only 3. Can someone try to help me ? ## First Word Frequency calculation: from nltk.corpus import stopwords import string stop_list = stopwords.words('english') + list(string.punctuation) tokens_no_stop = [token for token in tokens if token not in stop_list] word_frequency_no_stop = Counter(tokens_no_stop) for word, freq in word_frequency_no_stop.most_common(20): print(word, freq) Data 7 projects 5 People 4 systems 4 High 4 ## Second Word Frequency calc: all_tokens_lower = [t.lower() for t in word_frequency_no_stop] total_term_frequency_normalised = Counter(all_tokens_lower ) for word, freq in total_term_frequency_normalised.most_common(20): print(word, freq) data 2 project 2 management 2 skills 2 Does someone can explain why ?
1
1
0
0
0
0
I trying to tokenize by data using sent_tokenize and word_tokenize. Below is my dummy data **text** Hello world, how are you I am fine, thank you! I am trying to tokenize it using below code import pandas as pd from nltk.tokenize import word_tokenize, sent_tokenize Corpus=pd.read_csv(r"C:\Users\Desktop\NLP\corpus.csv",encoding='utf-8') Corpus['text']=Corpus['text'].apply(sent_tokenize) Corpus['text_new']=Corpus['text'].apply(word_tokenize) but it is giving below error Traceback (most recent call last): File "C:/Users/gunjit.bedi/Desktop/NLP Project/Topic Classification.py", line 24, in <module> Corpus['text_new']=Corpus['text'].apply(word_tokenize) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 3192, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\__init__.py", line 128, in word_tokenize sentences = [text] if preserve_line else sent_tokenize(text, language) File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\__init__.py", line 95, in sent_tokenize return tokenizer.tokenize(text) File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1241, in tokenize return list(self.sentences_from_text(text, realign_boundaries)) File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1291, in sentences_from_text return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1291, in <listcomp> return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1281, in span_tokenize for sl in slices: File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1322, in _realign_boundaries for sl1, sl2 in _pair_iter(slices): File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 313, in _pair_iter prev = next(it) File "C:\ProgramData\Anaconda3\lib\site-packages ltk\tokenize\punkt.py", line 1295, in _slices_from_text for match in self._lang_vars.period_context_re().finditer(text): TypeError: expected string or bytes-like object I did try a lot of things like if I comment sent_tokenize , the word_tokenize works but both of them do not work together
1
1
0
0
0
0
I have tried to use the minimax algorithm to make a program that cannot lose in tic tac toe. But, in a few cases, it is failing. For example, when there are two spots left on the tic tac toe board (in a few cases), the program stops playing and asks the user for two consecutive inputs. Also, in some cases when there is an obvious win for the computer it is not making the right choice of moves. This is for an assignment, and any kind of help today would be really appreciated. Thanks a lot! Edit: Please note that the code allows the user to overwrite previous moves. I will fix that as soon as I can get this working. However, even if I don't overwrite the previous chances, I don't get results. I have tested the code and the problem seems to be in the minimax function, but I've kept the whole code in case I'm wrong and the real problem lies elsewhere. Edit 2: Sorry for the incomplete post! The test case to reproduce the problem is below. After I enter my move (position 5), the program stops playing and asks me to play all the chances. Would you like to go first (Y/N)?: n . . . . . . . . . x . . . . . . . . Enter your choice (1-9): 5 x . . . o . . . . x x . . o . . . . Enter your choice (1-9): 7 x x . . o . o . . x x . . o . o . . Enter your choice (1-9): Also, I know my code is messy and amateur - but despite using global variables, I should be able to make it work. If you can help me with this I'll clean it all up. Thanks again! Edit 3: Another test case: Would you like to go first (Y/N)?: y . . . . . . . . . Enter your choice (1-9): 5 . . . . o . . . . x . . . o . . . . Enter your choice (1-9): 3 x . o . o . . . . x . o . o . x . . Enter your choice (1-9): 2 x o o . o . x . . x o o . o . x . . Enter your choice (1-9): 6 x o o . o o x . . x o o . o o x . . Enter your choice (1-9): 9 You win! My code is in Python 3.6 and is below: move = -1 n = 0 def evaluateBoard(board): global n #Checking for rows cnt = 0 for i in range(n): res = 0 for j in range(n): res += board[cnt * n + j] cnt += 1 if res == n: return 1 elif res == -n: return -1 #Checking for columns for i in range(n): res = 0 for j in range(n): res += board[i + n * j] if res == n: return 1 elif res == -n: return -1 #Checking for diagonals res = res2 = 0 for i in range(n): res += board[i * (n + 1)] res2 += board[(i + 1) * (n - 1)] if n in [res, res2]: return 1 elif -n in [res, res2]: return -1 return 0 def checkNonTerminal(board): for pos in board: if pos == 0: return 1 return 0 def getScore(board, depth): if evaluateBoard(board) == 1: return 10 - depth elif evaluateBoard(board) == -1: return depth - 10 else: return 0 def minimax(board, turn, depth): if evaluateBoard(board) == 0 and checkNonTerminal(board) == 0: return getScore(board, depth) global move moves = list() scores = list() for square, pos in enumerate(board): if pos == 0: #print(board) new_board = board.copy() new_board[square] = turn moves.append(square) #print("Moves:", moves, "depth:", depth, "turn:", turn, checkNonTerminal(new_board) == 0) if evaluateBoard(new_board) in [1, -1] or checkNonTerminal(new_board) == 0: return getScore(new_board, depth) scores.append(minimax(new_board, turn * -1, depth + 1)) #print("scores", scores) if turn == 1: move = moves[scores.index(max(scores))] return max(scores) elif turn == -1: move = moves[scores.index(min(scores))] return min(scores) def displayBoard(board): global n for i in range(n): for j in range(n): if board[n*i+j] == 1: print("x", end = " ") elif board[n*i+j] == -1: print("o", end = " ") else: print(".", end = " ") print() def main(): global n global move n = 3 first_turn = input("Would you like to go first (Y/N)?: ") if first_turn in ['Y', 'y']: first_turn = -1 cnt = 1 else: first_turn = 1 cnt = 2 board = [0] * 9 while evaluateBoard(board) == 0 and checkNonTerminal(board) == 1: displayBoard(board) if cnt % 2 == 0: score = minimax(board, 1, 0) print(score) board[move] = 1 else: choice = eval(input("Enter your choice (1-9): ")) board[choice - 1] = -1 cnt += 1 if evaluateBoard(board) == 1: print("You lose!") elif evaluateBoard(board) == -1: print("You win!") else: print("It's a draw!") main()
1
1
0
0
0
0
I am new to machine learning. I have one doubt: why use toarray() with onehotencoding while not with label encoding here. I am not getting any idea. pls someone help. from sklearn.preprocessing import LabelEncoder, OneHotEncoder label_encoder_x = LabelEncoder() x[:, 0] = label_encoder_x.fit_transform(x[:, 0]) onehotencoder = OneHotEncoder(categorical_features= [0]) x = onehotencoder.fit_transform(x).toarray() label_encoder_y = LabelEncoder() y = label_encoder_y.fit_transform(y)
1
1
0
1
0
0
I'm planning to break the paragraph into multiple sentences. This paragraph contains numbered sentences like shown below: Hello, How are you? Hope everything is good. I'm fine. 1.Hello World. 2.Good Morning John. Product is good but the managemnt is very lazy very bad. I dont like company service. They are giving fake promises. Next time i will not take any product. For Amazon service i will give 5 star dey give awsome service. But for sony company i will give 0 star... 1. Doesn't support all file formats when you connect USB 2. No other apps than YouTube and Netflix (requires subscription) 3. Screen mirroring is not up to the mark ( getting connected after once in 10 attempts 4. Good screen quality 5. Audio is very good 6. Bulky compared to other similar range 7. Price bit high due to brand value 8. its 1/4 smart TV. Not a full smart TV 9. Bad customer support 10. Remote control is very horrible to operate. it might be good for non smart TV 11. See the exchange value on amazon itself. LG gets 2ooo/- more than TV's 12. Also it was mentioned like 1+1 year warranty. But either support or Amazon support aren't clear about it. 13. Product information isn't up to 30% at least.There no installation. While I contact costumer Care. I had used the below code to break into sentences: import nltk tokenizer = nltk.tokenize.punkt.PunktSentenceTokenizer() fp = open("/Users/Desktop/sample.txt", encoding='utf-8') data = fp.read() with open("/Users/Desktop/output.txt", 'a', encoding='utf-8' ) as f: f.write(''.join(tokenizer.tokenize(data))) f.close() This code is splitting the paragraph based on full stops. But the numbered sentence are creating an issue. Since these have fullstops after numbers, it is splitting in an improper manner. Can anyone please suggest me regarding the same?
1
1
0
0
0
0
I am using gender guesser library to guess gender from first name. import gender_guesser.detector as gender d = gender.Detector() print(d.get_gender(u"Bob")) male gen = ['Alice', 'Bob', 'Kattie', "Jean", "Gabriel"] female male female male male But when I try to iterate it over pandas dataframe I get output as unknown for name in df1['first_name'].iteritems(): print(d.get_gender(name))
1
1
0
1
0
0
I am running NLP algorithms on Google Cloud but i notice that they are not quicker than my computer. When I go on the monitor, the CPU is limited to 15%. Is there a way to reach 100%? CPU Performance on NLP algorithm on Python
1
1
0
0
0
0
I have a data frame with a column gender. It consists of predictions of the gender. Now the gender column has values such as mostly_male, mostly_female. I want to remove mostly. So I trieddf['gender'] = df['gender'].map(lambda x: x.lstrip('mostly_')) But I got a column with values of 'male' corresponding to 'ale'
1
1
0
0
0
0
I did some research and found that gensim has a script to convert glove to word2vec GLove2Wrod2Vec. I am looking to do the opposite. Is there any simple way to convert using gensim or any other library
1
1
0
0
0
0
I am trying to train a Keras test summarization model to generate a new headline for a news article that I can then compare to the published headline. I am training on GloVe 6B, then predicting against the article, which I have cleaned by removing tags, parsing, removing stop words, lemmatized, and then rejoined. My results tend to look like this: Original Headline: Ford Traveled To Maryland In August Despite Allegedly Fear Of Flying Generated Headline: opinion: the the the the to to Article text after cleaning: Brett Kavanaugh accuser Christine Blasey Ford took polygraph test Maryland far home California despite alleged fear flying Documents released Wednesday polygraph test administered Ford Aug. 7 Hilton Hotel Linthicum Heights Maryland far Baltimore Washington International Airport A friend Kate DeVarney Blasey Ford enjoy flying hard time place ’s escape route Christine Blasey Ford professor accusing Supreme Court nominee Brett Kavanaugh having sexually assaulted high school previously told friend alleged encounter 30 year ago lasting effect life Two longtime friend Ford ’s told CNN week previously described feeling uncomfortable struggling enclosed space escape route exit door suggested discomfort stemmed alleged encounter Kavanaugh This reason Ford enjoy flying DeVarney said airplane ultimate closed space away The fear flying Ford able testify timely manner Senate Judiciary In letter California Democratic Sen. Dianne Feinstein dated July 30 2018 Ford said vacation Mid Atlantic Aug. 7 day polygraph given Ford testify Senate 10 a.m. EST Thursday Here is my training code: from __future__ import print_function import pandas as pd from sklearn.model_selection import train_test_split from keras_text_summarization.library.utility.plot_utils import plot_and_save_history from keras_text_summarization.library.seq2seq import Seq2SeqGloVeSummarizer from keras_text_summarization.library.applications.fake_news_loader import fit_text import numpy as np LOAD_EXISTING_WEIGHTS = False def main(): np.random.seed(42) data_dir_path = './data' very_large_data_dir_path = './very_large_data' report_dir_path = './reports' model_dir_path = './models' print('loading csv file ...') df = pd.read_csv("dcr Man_Cleaned.csv") print('extract configuration from input texts ...') Y = df.Title X = df['Joined'] config = fit_text(X, Y) print('configuration extracted from input texts ...') summarizer = Seq2SeqGloVeSummarizer(config) summarizer.load_glove(very_large_data_dir_path) if LOAD_EXISTING_WEIGHTS: summarizer.load_weights(weight_file_path=Seq2SeqGloVeSummarizer.get_weight_file_path(model_dir_path=model_dir_path)) Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.2, random_state=42) print('training size: ', len(Xtrain)) print('testing size: ', len(Xtest)) print('start fitting ...') history = summarizer.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=20, batch_size=16) history_plot_file_path = report_dir_path + '/' + Seq2SeqGloVeSummarizer.model_name + '-history.png' if LOAD_EXISTING_WEIGHTS: history_plot_file_path = report_dir_path + '/' + Seq2SeqGloVeSummarizer.model_name + '-history-v' + str(summarizer.version) + '.png' plot_and_save_history(history, summarizer.model_name, history_plot_file_path, metrics={'loss', 'acc'}) if __name__ == '__main__': main() Any thoughts as to what is going wrong here is appreciated.
1
1
0
0
0
0
I am just starting to work with Spacy and have put a text through to test how it is working on a pdf I OCR'd with AntFileConverter. The txt file (sample below - would attach but unsure how) seems fine, is in UTF-8. However when I output the file in CONLL format, for some reason there are various apparent gaps, which have no original word, but seem to have been identified. This happens both at the end and within sentences. "species in many waters in the northern hemisphere. In most countries in the region pike has both commercial and recreational value (Crossman & Casselman 1987; Raat 1988). Pike is a typical sit-and-wait predator which usually hunts prey by ambushing (Webb & Skadsen 1980)." The output us as so: GPE 24 26 species specie NNS 20 attr 27 in in IN 26 prep 28 many many JJ 29 amod 29 waters water NNS 27 pobj 30 in in IN 29 prep 31 the the DT 33 det 32 northern northern JJ 33 amod 33 hemisphere hemisphere NN 30 pobj 34 . . . 20 punct 1 In in IN 9 prep 2 GPE 1 3 most most JJS 4 amod 4 countries country NNS 9 nsubj 5 in in IN 4 prep 6 the the DT 8 det 7 region region NN 8 compound 8 pike pike NN 5 pobj 9 has have VBZ 0 ROOT 10 both both DT 11 preconj 11 commercial commercial JJ 9 dobj 12 GPE 11 13 and and CC 11 cc 14 recreational recreational JJ 15 amod 15 value value NN 11 conj 16 ( ( -LRB- 15 punct 17 Crossman crossman NNP ORG 15 appos 18 & & CC ORG 17 cc 19 Casselman casselman NNP ORG 17 conj 20 1987 1987 CD DATE 17 nummod 21 ; ; : 15 punct 22 GPE 21 23 Raat raat NNP 15 appos 24 1988 1988 CD DATE 23 nummod 25 ) ) -RRB- 15 punct 26 . . . 9 punct 1 Pike pike NNP 2 nsubj 2 is be VBZ 0 ROOT 3 a a DT 10 det 4 typical typical JJ 10 amod 5 sit sit NN 10 nmod 6 - - HYPH 5 punct 7 and and CC 5 cc 8 - - HYPH 9 punct 9 wait wait VB 5 conj 10 predator predator NN 2 attr 11 GPE 10 12 which which WDT 14 nsubj 13 usually usually RB 14 advmod 14 hunts hunt VBZ 10 relcl 15 prey prey NN 14 dobj 16 by by IN 14 prep 17 ambushing ambush VBG 16 pcomp 18 ( ( -LRB- 17 punct 19 Webb webb NNP 17 conj 20 & & CC 19 cc 21 I also tried without the NER print out but these gaps continue to be marked. I thought it might be related to the line breaks, so I also tried with a Linux-style EOL but that didn't make any difference. This is the code I am using: import spacy import en_core_web_sm nlp_en = en_core_web_sm.load() input = open('./input/55_linux.txt', 'r').read() doc = nlp_en(input) for sent in doc.sents: for i, word in enumerate(sent): if word.head == word: head_idx = 0 else: head_idx = word.head.i - sent[0].i + 1 output = open('CONLL_output.txt', 'a') output.write("%d\t%s\t%s\t%s\t%s\t%s\t%s "%( i+1, # There's a word.i attr that's position in *doc* word, word.lemma_, word.tag_, # Fine-grained tag word.ent_type_, str(head_idx), word.dep_ # Relation )) Has anyone else had this problem? If so, do you know how I can solve it?
1
1
0
0
0
0
I am working on implementing a program that will give me the result for the Positional inverted index of an xml file. First I need to change the type of document number from string to int in order to use it later on. Some of my code is the following: def index(document_directory, dictionary_file, postings_file): # preprocess docID list docID_list = [int(docID_string) for docID_string in os.listdir(document_directory)] docID_list.sort() stemmer = PorterStemmer() stopwords = nltk.corpus.stopwords.words('english') # stopwords = set(stopwords.words('english')) docs_indexed = 0 # counter for the number of docs indexed dictionary = {} # key: term, value: docIDs containing term (incudes repeats) # for each document in corpus for docID in docID_list: if (LIMIT and docs_indexed == LIMIT): break . . . . . # open files for writing dict_file = codecs.open(dictionary_file, 'w', encoding='utf-8') post_file = open(postings_file, 'wb') . . . . # close files dict_file.close() post_file.close() . . . . """ prints the proper command usage """ def print_usage(): print ("usage: " + sys.argv[0] + "-i directory-of-documents -d dictionary-file -p postings-file") . . . if (RECORD_TIME): start = timeit.default_timer() # start time index(document_directory, dictionary_file, postings_file) # call the indexer if (RECORD_TIME): stop = timeit.default_timer() # stop time if (RECORD_TIME): print ('Indexing time:' + str(stop - start)) # print time taken Now when I run it using the command: $ python def_ind.py -i "./index/" -d "output1111.txt" -p "output222.txt" I get the following error: Traceback (most recent call last): File "def_ind.py", line 161, in <module> index(document_directory, dictionary_file, postings_file) # call the indexer File "def_ind.py", line 36, in index docID_list = [int(docID_string) for docID_string in os.listdir(document_directory)] File "def_ind.py", line 36, in <listcomp> docID_list = [int(docID_string) for docID_string in os.listdir(document_directory)] ValueError: invalid literal for int() with base 10: '.DS_Store' I understand that there is a string that can't be int, but I didn't know how? What am supposed to do in here? I am trying to get output that will check each word how many times appeared in each document number and in which line. for example:(document number: line number where the word found) and: 2: 5,7 5: 5 flower: 1: 8 2: 4,6,8 3: 6 4: 6 5: 6 snapshot from my xml file: <DOCNO>1</DOCNO> <PROFILE>_AN-BENBQAD8FT</PROFILE> <DATE>910514 </DATE> <HEADLINE> FT 14 MAY 91 / (CORRECTED) Jubilee of a jet that did what it was designed to do </HEADLINE> <TEXT> words, words, words </TEXT> <PUB>The Financial Times </PUB> <PAGE> London Page 7 Photograph (Omitted). </PAGE> </DOC>` I am using python 3.7. Note: I found many questions with the same error but non of them suited my situation.
1
1
0
0
0
0
i want to search a specific word(which is entered by user) in .xml file. This is my xml file. <?xml version="1.0" encoding="UTF-8"?> <words> <entry> <word>John</word> <pron>()</pron> <gram>[Noun]</gram> <poem></poem> <meanings> <meaning>name</meaning> </meanings> </entry> </words> here is my Code import nltk from nltk.tokenize import word_tokenize import os import xml.etree.ElementTree as etree sen = input("Enter Your sentence - ") print(sen) print(" ") print(word_tokenize(sen)[0]) tree = etree.parse('roman.xml') node=etree.fromstring(tree) #node=etree.fromstring('<a><word>waya</word><gram>[Noun]</gram> <meaning>talking</meaning></a>') s = node.findtext(word_tokenize(sen)[0]) print(s) i have tried everything but still its giving me error a bytes-like object is required, not 'ElementTree' i really don't know how to solve it.
1
1
0
0
0
0
I have been trying to make my enemy spawn every 20 seconds to counteract the fact that the enemy gets stuck underneath platforms when it is directly bellow the player, I have left the method that I was going to use, however I have not had much luck implementing it. The plan was to use the timer.tick built into python to be able to time every 20 seconds, however I realised that this just worked on the frame rate, as you can see at the top I used start = time.time() to begin the clock, and then write end = time.time() to end the clock after 20 seconds. import pygame #imports pygame import time #imports the timer so I can use the tick function to make game 60fps start= time.time() #for every function write this end= time.time() import math #imports maths import sys #imports system import random from random import * from time import * #imports all modules from time from pygame import * #imports all pygame files from pygame.math import * from pygame.mixer import * print(start) win_height = 750 #height of window is 750 pixles win_width = 1050 #height of window is 1050 pixels half_win_width = int(win_width / 2) #will be used to centre camera half_win_height = int(win_height / 2) white=(255, 255, 255) black=(0, 0, 0) gray=(50, 50, 50) red=(255, 0, 0) green=(0, 255, 0) blue=(0, 0, 255) yellow=(255, 255, 0) display = (win_width, win_height) #creates the window as 500*500 pixels depth = 32 #prevents infinate recursion flags = 0 #message to Les: I don't really know what this does, however I have seen it in many places being used, therefore I assumed that it was important camera_slack = 30 #how many pixels the player can move before the camera moves with them pygame.init() mixer.init() pygame.mixer.music.load('Caravan Palace - Lone Digger [Clip officiel].mp3') #plays music within my game folder #pygame.mixer.music.load('Toby Fox - Megalovania [Electro Swing Remix].mp3') #plays music within my game folder pygame.mixer.music.play(-1) #loops music infinately myfont = pygame.font.SysFont('Comic Sans MS', 30) def main_menu(): pygame.init() screen = pygame.display.set_mode(display, flags, depth) pygame.display.set_caption("Super Castlevania Man") timer = pygame.time.Clock() def main(): #main game function global cameraX, cameraY pygame.init() screen = pygame.display.set_mode(display, flags, depth) pygame.display.set_caption("Super Castlevania Man") timer = pygame.time.Clock() move_cameraX = 0 move_cameraY = 0 up = down = left = right = running = False background = pygame.Surface((32,32)) #the background takes up space on the screen background.convert() background.fill(pygame.Color("#000000")) #background is black entities = pygame.sprite.Group() player = Player_class(32, 32*15) #the player is 32*32 pixels large platforms = [] x = y = 0 blank_level = [ "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "P P", "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"] def print_level(level): for row in level: print(row) new_level = blank_level #Randomly Generate levels #First do the platforms #Pick a random number of platforms (6 - 12) #For those then pick a row which doesn't have one on (I.e. only has two Ps in), and pick a start cell and a length (3-7) -> ensure it cuts off @ wall #Pick a random empty cell for E to go into for z in range (0,15): plat_len = (randint(1, 7)) plat_start = (randint(3, 29)) row = (randint(3, 19)) new_level[row] = new_level[row][0:plat_start]+("P"*plat_len)+new_level[row][plat_start+plat_len:] #Pick a random empty cell for E to go into new_level[5] = new_level[5][0:4]+"E"+new_level[5][5:] for row in blank_level: for col in row: if col == "P": p = Platform(x, y) #makes P a solid object platforms.append(p) entities.add(p) if col == "E": e = Exit_block(x, y) platforms.append(e) entities.add(e) x += 32 y += 32 x = 0 entities.add(player) enemy = Enemy(60, 200, player) #Spawns enemy enemy_list = pygame.sprite.Group() #creates an enemy group enemy_list.add(enemy) #Add an enemy to the group while 1: timer.tick(60) #makes game run at 60 frames per second for e in pygame.event.get(): #shortens event to e if e.type == QUIT: return if e.type == KEYDOWN and e.key == K_ESCAPE: return if e.type == KEYDOWN and e.key == K_UP: up = True move_cameraY = -10 if e.type == KEYDOWN and e.key == K_DOWN: down = True move_cameraY = 10 if e.type == KEYDOWN and e.key == K_LEFT: left = True move_cameraX = -10 if e.type == KEYDOWN and e.key == K_RIGHT: right = True move_cameraX = 10 if e.type == KEYDOWN and e.key == K_SPACE: running = True if e.type == KEYUP and e.key == K_UP: up = False move_cameraY = 0 if e.type == KEYUP and e.key == K_DOWN: down = False move_cameraY = 0 if e.type == KEYUP and e.key == K_RIGHT: right = False move_cameraX = 0 if e.type == KEYUP and e.key == K_LEFT: left = False move_cameraX = 0 if e.type == KEYUP and e.key == K_RIGHT: right = False # Update the game. for e in enemy_list: e.update(platforms) player.update(up, down, left, right, running, platforms) # Draw everything. for y in range(32): #draws the background for x in range(32): screen.blit(background, (x * 32, y * 32)) entities.draw(screen) enemy_list.draw(screen) pygame.display.flip() # You need only one flip or update call per frame. class Entity(pygame.sprite.Sprite): #makes player a sprite def __init__(self): pygame.sprite.Sprite.__init__(self) #sets sprite to initiate class Player_class(Entity): #defines player class def __init__(self, x, y): #x is the player x coordinate, y is the player y coordinate Entity.__init__(self) #the player is an entity self.xvel = 0 #how fast the player is moving left and right self.yvel = 0 #how fast the player is moving up and down self.onGround = False #assumes the player is in the air self.image = pygame.Surface((32,32)) #the player is 32*32 pixels self.image.fill(pygame.Color("#0000FF")) #makes the player blue self.rect = pygame.Rect(x, y, 32, 32) self.x = x self.y = y def update(self, up, down, left, right, running, platforms): if up: if self.onGround: self.yvel -= 10 #only jump if player is on the ground if down: pass if running: self.xvel = 12 if left: self.xvel = -8 if right: self.xvel = 8 if not self.onGround: self.yvel += 0.3 #only accelerate with gravity if in the air if self.yvel > 100: self.yvel = 100 #terminal velocity = 100 if not(left or right): self.xvel = 0 self.rect.left += self.xvel #falls or jumps self.collide(self.xvel, 0, platforms) #creates collisions along the x axis self.rect.top += self.yvel #creates collisions along the y axis self.onGround = False; #assumes that the player is in the air # do y-axis collisions self.collide(0, self.yvel, platforms) def collide(self, xvel, yvel, platforms): for p in platforms: if pygame.sprite.collide_rect(self, p): if isinstance(p, Exit_block): pygame.quit() sys.exit() if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = p.rect.bottom class Platform(Entity): def __init__(self, x, y): Entity.__init__(self) self.image = pygame.Surface((32, 32)) self.image.fill(pygame.Color("#FFFFFF")) self.rect = pygame.Rect(x, y, 32, 32) class Exit_block(Platform): def __init__(self, x, y): Platform.__init__(self, x, y) self.image.fill(pygame.Color("#00FF00"))#exit block is green class Enemy(Entity): def __init__(self, x, y, player): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((32, 32)) self.xvel = 0 self.yvel = 0 self.image.fill(pygame.Color("#FF0000")) #Enemy is red self.rect = pygame.Rect(250, 50, 32, 32) # # # # """ if pygame.time.Clock == 20: self.rect = pygame.Rect(250, 50, 32, 32) """ self.player = player def collide(self, xvel, yvel, platforms): # Check if the enemy collides with the player. if self.rect.colliderect(self.player.rect): pygame.quit() sys.exit() for p in platforms: if pygame.sprite.collide_rect(self, p): if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top if yvel < 0: self.rect.top = p.rect.bottom def move(self, xvel, platforms, speed=4): # chase movement for p in platforms: #if the top of the enemy is touching the bottom of a platform, move the enemy to the right if pygame.sprite.collide_rect(self, p): if xvel == 15: self.rect.top = p.rect.bottom if self.rect.x > self.player.rect.x: # Movement along x direction self.xvel = -speed elif self.rect.x < self.player.rect.x: self.xvel = speed if self.rect.y < self.player.rect.y: # Movement along y direction self.yvel = speed elif self.rect.y > self.player.rect.y: self.yvel = -speed def update(self, platforms): self.move(self, platforms) # Set the velocity. self.rect.left += self.xvel self.collide(self.xvel, 0, platforms) #creates collisions along the x axis self.rect.top += self.yvel #creates collisions along the y axis self.collide(0, self.yvel, platforms) if __name__ == "__main__": main() pygame.quit()
1
1
0
0
0
0
I'm trying to use tensorflow to run classify_image.py, but I keep getting the same error: Traceback (most recent call last): File "classify_image.py", line 46, in <module> import tensorflow as tf File "C:\Users\Diederik\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py", line 22, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import ModuleNotFoundError: No module named 'tensorflow.python' Someone asked me to do a pip3 list, so I did: C:\Users\Diederik\AppData\Local\Programs\Python\Python36\Scripts>pip3 list Package Version ----------- ------- absl-py 0.3.0 astor 0.7.1 gast 0.2.0 grpcio 1.13.0 Markdown 2.6.11 numpy 1.15.0 pip 10.0.1 protobuf 3.6.0 setuptools 39.0.1 six 1.11.0 tensorboard 1.9.0 tensorflow 1.9.0** termcolor 1.1.0 Werkzeug 0.14.1 wheel 0.31.1 You are using pip version 10.0.1, however version 18.0 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command.
1
1
0
0
0
0
I have a pre-defined list of words; e.g.: wordlist = [["one"],["two"],["three"]] And I have a large corpus of .txt files, also imported into python as a list, e.g.: corpus = ["my friend has one potato", "i have two bananas and three apples", "my dad has three apples"] I want a formula that goes through the corpus line by line and tells me the amount of words from my wordlist that are contained in each line; i.e., exemplary output would be: 1 2 1 I need no differentiation between the words in the wordlist. However, I want this to be a formula, so that I can easily apply it with different word lists or corpora. I have not found an answer on SO or elsewhere. What I have tried is: wordcount_total=list() for i in range(len(corpus)): row=corpus[i] wordcount_row=sum(1 for word in row.split() if word in wordlist) wordcount_total.append(wordcount_row) However, this gives me: 0 0 0 Many thanks to anyone willing to help!
1
1
0
0
0
0
I have a sample of ~60,000 documents. We've hand coded 700 of them as having a certain type of content. Now we'd like to find the "most similar" documents to the 700 we already hand-coded. We're using gensim doc2vec and I can't quite figure out the best way to do this. Here's what my code looks like: cores = multiprocessing.cpu_count() model = Doc2Vec(dm=0, vector_size=100, negative=5, hs=0, min_count=2, sample=0, epochs=10, workers=cores, dbow_words=1, train_lbls=False) all_docs = load_all_files() # this function returns a named tuple random.shuffle(all_docs) print("Docs loaded!") model.build_vocab(all_docs) model.train(all_docs, total_examples=model.corpus_count, epochs=5) I can't figure out the right way to go forward. Is this something that doc2vec can do? In the end, I'd like to have a ranked list of the 60,000 documents, where the first one is the "most similar" document. Thanks for any help you might have! I've spent a lot of time reading the gensim help documents and the various tutorials floating around and haven't been able to figure it out. EDIT: I can use this code to get the documents most similar to a short sentence: token = "words associated with my research questions".split() new_vector = model.infer_vector(token) sims = model.docvecs.most_similar([new_vector]) for x in sims: print(' '.join(all_docs[x[0]][0])) If there's a way to modify this to instead get the documents most similar to the 700 coded documents, I'd love to learn how to do it!
1
1
0
0
0
0
I want to take square of the difference between the tensors/output after the LSTM layer and multiply it with the trainable parameter. As pointed out by @rvinas, I tried to write my own layer for the purpose, class MyLayer(Layer): def __init__(self,W_regularizer=None,W_constraint=None, **kwargs): self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.W_constraint = constraints.get(W_constraint) super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 # Create a trainable weight variable for this layer. self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint, trainable=True) super(MyLayer, self).build(input_shape) The call function is multiplying only the tensors and Weight which I have initialized. Still I need to find how to take the pairwise difference and square them. def call(self, x): uit = K.dot(x, self.W) return uit def compute_output_shape(self, input_shape): return input_shape[0], input_shape[-1] But then I am getting AssertionErrorat assert len(input_shape) >= 3. I want to perform: from keras.layers import Input, Lambda, LSTM from keras.models import Model import keras.backend as K from keras.layers import Lambda lstm=LSTM(128, return_sequences=True)(input) something=MyLayer()(lstm)
1
1
0
0
0
0
I have been working with relation extraction for a week. But what I need is direction between two entities, such as Company_x got bought by Company_y. So the model should predict the entities like Company_y->bought-> Company_X. Any models you guys think will be helpful for this?
1
1
0
0
0
0
I want to predict the location-based one training data. I have data in below format. Training Data: Address Location_id Location_name Flat No.201, MIDC, Andheri East, Mumbai, Maharashtra 121 Andheri East Business Park, Goregaon, Mumbai, Maharashtra 122 Goregaon Powai, Mumbai 123 Powai Andheri East, Mumbai 121 Andheri East Best Business Park, Goregaon, Mumbai 122 Goregaon Hiranandani Park, Powai, Mumbai 123 Powai Test Data: plot no. 121, MIDC Area, Andheri East, Mumbai Expected output: To predict the location ID and Location Name. Please suggest.
1
1
0
1
0
0
I have a large Bengali monolingual corpus which consists of over 100 million Bengali sentences. The corpus is in .txt format and the file size is 1.8 GB. Now, in order to build a Bengali Grammar checker, I need to use this enormous corpus to calculate Trigram language probability. However, this seems to take an enormous amount of time to find Trigram probability in such a large file. Please suggest how to solve this issue and which techniques should I use in this case. Should I use php or python for this? I have sufficient knowledge in both. TIA
1
1
0
0
0
0
I'm trying to combine text and categorical variables using Keras functional API. The model compiles but when I try to train the model using "fit", it gives me an error. Looks like the way I put the data is wrong. Has anyone ever done something similar and knows how to make it work? Code for building the model: all_inputs = [] cat_embeddings = [] text_input = Input(shape=(MAX_SEQUENCE_LENGTH, ),name='text_input') all_inputs.append(text_input) x = Embedding(embedding_matrix.shape[0], # or len(word_index) + 1 embedding_matrix.shape[1], # or EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=True)(text_input) x = SpatialDropout1D(0.2)(x) x = Bidirectional(GRU(128, return_sequences=True,dropout=0.1,recurrent_dropout=0.1))(x) x = Conv1D(64, kernel_size = 3, padding = "valid", kernel_initializer = "glorot_uniform")(x) x = GlobalMaxPooling1D()(x) x = Dense(128, activation='relu')(x) for cat in Categorical_Features: cat_input = Input(shape=(1,), name=cat) no_of_unique_cat = X_train[cat].nunique() embedding_size = np.ceil((no_of_unique_cat)/2) embedding_size = int(embedding_size) cat_embedding = Embedding(no_of_unique_cat+1, embedding_size, input_length = 1)(cat_input) cat_embedding = Reshape(target_shape=(embedding_size,))(cat_embedding) all_inputs.append(cat_input) cat_embeddings.append(cat_embedding) conc = Concatenate()(cat_embeddings) x = concatenate([conc, x]) x = Dense(128, activation='relu')(x) x = Dropout(0.1)(x) x = Dense(128, activation='relu')(x) x = Dropout(0.1)(x) x = Dense(128, activation='relu')(x) preds = Dense(93, activation="sigmoid")(x) model = Model(inputs=all_inputs, outputs=preds) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=1e-3), metrics=['accuracy']) Then I try to put the data in this way: model.fit([X_train_seq, X_train['Categorical_Features_1'], X_train['Categorical_Features_2'], X_train['Categorical_Features_3'], X_train['Categorical_Features_4'], X_train['Categorical_Features_5'], X_train['Categorical_Features_6']] , y_train, validation_split=0.2, class_weight = d_class_weights, epochs=5, batch_size=512) Then I get this error: InvalidArgumentError: indices[460,0] = 421 is not in [0, 406) [[{{node embedding_18/GatherV2}} = GatherV2[Taxis=DT_INT32, Tindices=DT_INT32, Tparams=DT_FLOAT, _class=["loc:@training_8/Adam/gradients/embedding_18/GatherV2_grad/Reshape"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_18/embeddings/read, embedding_18/Cast, embedding_17/GatherV2/axis)]] This code is inspired by the code in this Kaggle competition: https://www.kaggle.com/aquatic/entity-embedding-neural-net and the paper "Entity Embeddings of Categorical Variables": https://arxiv.org/abs/1604.06737
1
1
0
0
0
0
I have imported text data into pandas dataframe. I would like to implement Vectorizer. So i use sklearn to do tfidf and so on So the first step i did. clean the text. #Creating Function from nltk.corpus import stopwords def text_process(sms): nonpunc = [char for char in sms if char not in string.punctuation] nonpunc = ''.join(nonpunc) return[word for word in nonpunc.split() if word.lower() not in stopwords.words('english')] Next data['sms'].head(5).apply(text_process) Next from sklearn.feature_extraction.text import CountVectorizer bow_transformer = CountVectorizer(analyzer = text_process).fit(data['sms']) I receive an error. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-84-f1812582c7e1> in <module> 1 #Step 1 2 from sklearn.feature_extraction.text import CountVectorizer ----> 3 bow_transformer = CountVectorizer(analyzer = text_process).fit(data['sms']) ~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit(self, raw_documents, y) 976 self 977 """ --> 978 self.fit_transform(raw_documents) 979 return self 980 ~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y) 1010 1011 vocabulary, X = self._count_vocab(raw_documents, -> 1012 self.fixed_vocabulary_) 1013 1014 if self.binary: ~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in _count_vocab(self, raw_documents, fixed_vocab) 920 for doc in raw_documents: 921 feature_counter = {} --> 922 for feature in analyze(doc): 923 try: 924 feature_idx = vocabulary[feature] <ipython-input-82-4149ae75d7bf> in text_process(sms) 3 def text_process(sms): 4 ----> 5 nonpunc = [char for char in sms if char not in string.punctuation] 6 nonpunc = ''.join(nonpunc) 7 return[word for word in nonpunc.split() if word.lower() not in stopwords.words('english')] TypeError: 'NoneType' object is not iterable
1
1
0
0
0
0
When trying to run a simple get data sequence on Jupyter, for a system to recognise the iris flower tyoes teough fisher's table, the error: ValueError Traceback (most recent call last) <ipython-input-12-269564554b65> in <module> 10 training_set = base.load_csv_with_header(filename=IRIS_TRAINING, 11 features_dtype=np.float32, ---> 12 target_dtype=np.float32) 13 test_set = base.load_csv_with_header(filename=IRIS_TEST, 14 features_dtype=np.float32, /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py in load_csv_with_header(filename, target_dtype, features_dtype, target_column) 46 data_file = csv.reader(csv_file) 47 header = next(data_file) ---> 48 n_samples = int(header[0]) 49 n_features = int(header[1]) 50 data = np.zeros((n_samples, n_features), dtype=features_dtype) ValueError: invalid literal for int() with base 10: '5.1' is being shown. The error indicates that it is unable to use the int() function despite the fact that there is no int in the code at all. Here is the code: import tensorflow as tf import numpy as np from tensorflow.contrib.learn.python.learn.datasets import base # Data files IRIS_TRAINING = "iris_training.csv" IRIS_TEST = "iris_test.csv" # Load datasets. training_set = base.load_csv_with_header(filename=IRIS_TRAINING, features_dtype=np.float32, target_dtype=np.float32) test_set = base.load_csv_with_header(filename=IRIS_TEST, features_dtype=np.float32, target_dtype=np.float32) print(training_set.data) print(training_set.target) Why is target_dytype=np.int not working, as the error shows? Thanks in advance.
1
1
0
0
0
0
I'm working with Google Cloud NLP Api with Python(3.6), my client asked to get polar-opposite/replaced-word-for-opposite-word for every word of provided text file. Here's what I have tried: From views.py: if form.is_valid(): obj = form obj.textFile = form.cleaned_data['textFile'] obj.save() text_path = os.path.join(settings.MEDIA_ROOT, 'texts/', obj.textFile.name) txt = Path(text_path).read_text(encoding='cp1252') service = discovery.build('language', 'v1beta1', credentials=credentials) service_request = service.documents().analyzeSentiment( body={ 'document': { 'type': 'PLAIN_TEXT', 'content': txt } } ) response = service_request.execute() print(response) Here's the response: {'documentSentiment': {'polarity': 0.3, 'magnitude': 0.1, 'score': 0}, 'language': 'en', 'sentences': [{'text': {'content': 'hello!', 'beginOffset': -1}, 'sentiment': {'polarity': 1, 'magnitude': 0, 'score': 0}}, {'text': {'content': 'This is Abdul.', 'beginOffset': -1}, 'sentiment': {'polarity': -1, 'magnitude': 0, 'score': 0}}]} I have explored the documentation of Google's NLP API, but couldn't find any option to get polar opposite for every word. Is there any possible option to achieve this? Help me, please! Thanks in advance!
1
1
0
0
0
0
I am using 'nltk' installed by pip in my project. It works fine in local But when I tried to deploy in google appengine , It shows the Import error 'Cannot import name compat'. How to resolve it? Thanks in advance update: the code from nltk import word_tokenize, pos_tag, ne_chunk, tree2conlltags sentence = "Hi , This week has been crazy. My report is on IBM. Can you give it a quick read and provide some feedback. She is in London. John lives in New York and works for the European Union." ne_tree = ne_chunk(pos_tag(word_tokenize(sentence))) iob_tagged = tree2conlltags(ne_tree) print iob_tagged name = [] for chunk in iob_tagged: if chunk[2] != 'O': name.append(chunk[2]) else: name.append(chunk[0]) print name The error from nltk.corpus import wordnet, words File "/base/data/home/apps/s~/prod-2582.413469289899104484/lib/nltk/__init__.py", line 137, in <module> from nltk.stem import * File "/base/data/home/apps/s~/prod-2582.413469289899104484/lib/nltk/stem/__init__.py", line 29, in <module> from nltk.stem.snowball import SnowballStemmer File "/base/data/home/apps/s~/prod-2582.413469289899104484/lib/nltk/stem/snowball.py", line 31, in <module> from nltk import compat ImportError: cannot import name compat
1
1
0
0
0
0
I am trying to format the output into a table. For example all the matched files to be the columns and the matches instance should be the rows. Here is my code: import glob import re folder_path = "/home/e136320" file_pattern = "/*.txt" match_list = [] folder_contents = glob.glob(folder_path + file_pattern) #Search for Emails regex1= re.compile(r'\S+@\S+') #Search for Phone Numbers regex2 = re.compile(r'\d\d\d[-]\d\d\d[-]\d\d\d\d') #Search for Physician's Name regex3=re.compile(r'\b\w\w\.\w+\b') for file in folder_contents: read_file = open(file, 'rt').read() words=read_file.split() for line in words: email=regex1.findall(line) phone=regex2.findall(line) for word in email: print(file,email) for word in phone: print(file,phone) Here is my Output: ('/home/e136320/sample.txt', ['bcbs@aol.com']) ('/home/e136320/sample.txt', ['James@aol.com']) ('/home/e136320/sample.txt', ['248-981-3420']) ('/home/e136320/wow.txt', ['soccerfif@yahoo.com']) ('/home/e136320/wow.txt', ['313-806-6666']) ('/home/e136320/wow.txt', ['444-444-4444']) ('/home/e136320/wow.txt', ['248-805-6233']) ('/home/e136320/wow.txt', ['maliva@gmail.com']) Any Ideas?
1
1
0
0
0
0
I have a dataset provided properties.csv (4000 rows and 6 columns). The csv file including many features some of these features are numerical and some of them are nominal (features contain text). Suppose the features in this dataset are id F1 F2 F3 F4 Price Examples of the content of each feature: id (row 1 to 3 in CSV File) ---> 44525 44859 45465 F1 (row 1 to 3 in CSV File) ---> "Stunning 6 bedroom villa in the heart of the Golden Mile, Marbella" "Villa for sale in Rocio de Nagüeles, Marbella Golden Mile" "One level 5 bedroom villa for sale in Nagüeles" F2 (row 1 to 3 in CSV File) ---> "Fireplace, Elevator, Terrace, Mountain view, Freight Elevator, Air conditioning, Patio, Guest toilet, Garden, Balcony, Sea/lake view, Built-in kitchen" "Mountain view" "Elevator, Terrace, Alarm system, Mountain view, Swimming pool, Air conditioning, Basement, Sea/lake view" F3 (row 1 to 3 in CSV File) - contains numerical values ---> 0 0 0 F4 (row 1 to 3 in CSV File) - contains numerical values ---> 393 640 4903 F3 (row 1 to 3 in CSV File) - contains numerical values ---> 4400000 2400000 1900000 In F1, I am looking to do the following: 1- Extract the type of the properties (apartment’, ‘house’ or ‘Villa’) and put it in a separate feature (independent variable) calls "Type" in CSV file. After that, I want to separate them in groups (apartments group, houses group, Vilas group) with calculating the mean price of each type group. 2- Extract the location of each property (locations can be: Alenquer, Quinta da Marinha, Golden Mile, Nagüeles) and put it in a separate feature (independent variable) calls "Location" in csv file. I am a beginner in NLP. I tried to write this code to extract information "Apartment" from F1, but it does not work probably: import pandas as pd from pandas import DataFrame import re properties = pd.read_csv (r'C:/Users/User/Desktop/properties.csv') Extract "Apartment" from F1 Title= DataFrame(properties,columns= ['F1']) for line in F1: #return list of apartments in that line x = re.findall("\apartment", line) #if a date is found if len(x) != 0: print(x) I need your help to fix this code and what should I do to extract the other information ‘houses’ and ‘Villa’ from F1. After that, Create a property dataset in this format and save it as a csv file: id Location (Information extracted from F1) type (information extracted from F1 in groups "apartments’, ‘houses’, ‘Villas’") F1 F2 F3 F4 Price In case, F1 does not contain the type of some properties "Blank field (no text)", what should I do to deal with the blanks fields (no text) in F1 and extract the type of the properties from other properties?
1
1
0
0
0
0
I am thinking of summarizing the audio of Youtube videos using AI, machine learning, as a Hobby project. I am able to extract auto-generated Closed Caption text as a CLOB, given below: good day fellow investors I don't think I ever mentioned it but I'm subscribed to almost all out of there Bloomberg Wall Street Journal Morningstar and many others that I don't want to mention not to public publicize them because most don't deserve my money but still if even if I get a little bit from there it's good however something nice that came in the email yesterday was of course Wall Street Journal and I'm subscribed to their daily shot which gives a lot of slides about what's going on in the economy markets etc which is always nice to look at on a daily basis But as you can see it does not have any punctuation characters at all. I am planning to use python NLTK library, but the Sentence Tokenizer is unable to break the text into any sort of smaller chunks. I am new to NLP (as you can guess), can anyone please point me to an article, preferably a how to guide, to "punctuate a blob of text". I am not getting much help from google search (my bad). Please suggest a way ahead, thanks.
1
1
0
0
0
0
I've installed tensorflow over pip3 and python3, and am working on it. While using the colum function, the commonly experienced error AttributeError: module 'tensorflow' has no attribute 'feature_column'. It might look like a duplicate question, but I've looked at the other occurrences of the same question, but, after updating the file (pip3 install --upgrade tensorflow), I checked the version. The version 0.12.0 is shown. So why does pip still show its completely new. Is 0.12.0 the newest version? When I attempted to uninstall tensorflow and re-install it, it refuses to re-install. I'm using python3 -m pip install tensorflow. The error thrown here is Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow Thanks in advance for your help
1
1
0
0
0
0
I am trying to implement Minimum Edit Distance with the substitution cost of 2. Following is the code I've so far. It works well for strings of equal length but generates error for the unequal strings. Kindly correct me where i am wrong def med(source, target): # if len(x) > len(y): # print("insode if") # source, target = y, x print(len(source), len(target)) cost = [[0 for inner in range(len(source)+1)] for outer in range(len(target)+1)] global backtrace backtrace = [[0 for inner in range(len(source)+1)] for outer in range(len(target)+1)] global SUB global INS global DEL for i in range(0,len(target)+1): cost[i][0] = i for j in range(0,len(source)+1): cost[0][j] = j for i in range(1,len(target)+1): for j in range(1,len(source)+1): if source[i-1]==target[j-1]: cost[i][j] = cost[i-1][j-1] else: deletion = cost[i-1][j]+1 insertion = cost[i][j-1]+1 substitution = cost[i-1][j-1]+2 cost[i][j] = min(insertion,deletion,substitution) if cost[i][j] == substitution: backtrace[i][j] = SUB elif cost[i][j] == insertion: backtrace[i][j] = INS else: backtrace[i][j] = DEL return cost[i][j] med("levenshtein","levels") The error i get is: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-26-86bf20ea27c7> in <module>() 49 return cost[i][j] 50 ---> 51 med("levenshtein","levels") <ipython-input-26-86bf20ea27c7> in med(source, target) 31 for i in range(1,len(target)+1): 32 for j in range(1,len(source)+1): ---> 33 if source[i-1]==target[j-1]: 34 cost[i][j] = cost[i-1][j-1] 35 else: IndexError: string index out of range
1
1
0
0
0
0
Initially I had followed preprocessing steps like, stop words removal, HTML stripping, removing punctuation. However when I don't do this, the NER seems to perform better. Can anyone tell me what are preprocessing steps to be followed?
1
1
0
0
0
0
I am currently solving an exercise which involves reading in TED talks, labelling them according to the topics they are about, and training a Feed Forward NN in Keras that can label new talks accordingly, using pre-trained word embeddings. Depending on what the talk is about (technology, education or design or multiple of those topics), it can have one of the following labels: labels_dict = { 'txx': 0, 'xex': 1, 'xxd': 2, 'tex': 3, 'txd': 4, 'xed': 5, 'ted': 6, 'xxx': 7 } I load the talks like this: def load_talks(path): tree = et.parse(path) root = tree.getroot() for file in root: label = '' keywords = file.find('head').find('keywords').text.lower() if 'technology' in keywords: label += 't' else: label += 'x' if 'education' in keywords: label += 'e' else: label += 'x' if 'design' in keywords: label += 'd' else: label += 'x' talk = file.find('content').text talk = process_text(talk) texts.append(talk) labels.append(labels_dict[label]) I then calculate TF-IDF scores for the tokens in the texts: tf_idf_vect = TfidfVectorizer() tf_idf_vect.fit_transform(texts) tf_idf_vectorizer_tokens = tf_idf_vect.get_feature_names() Then I use a tokenizer to assign the tokens in the texts to indexes: t = Tokenizer() t.fit_on_texts(texts) vocab_size = len(t.word_index) + 1 encoded_texts = t.texts_to_sequences(texts) print('Padding the docs') # pad documents to a max length of 4 words max_length = max(len(d) for d in encoded_texts) padded_docs = pad_sequences(encoded_texts, maxlen=max_length, padding='post') Next, I compute the embedding matrix: def compute_embedding_matrix(word_index, embedding_dim): embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim)) for word, i in word_index.items(): embedding_vector = word_embeddings.get(word) if embedding_vector is not None and get_tf_idf_score(word) > TF_IDF_THRESHOLD: # words not found in embedding index and with a too low tf-idf score will be all-zeros. embedding_matrix[i] = embedding_vector return embedding_matrix embedding_dim = load_word_embeddings('word_embeddings/de/de.tsv') + 1 embedding_matrix = compute_embedding_matrix(t.word_index, embedding_dim) I then prepare the labels and split the data in training and testing: labels = to_categorical(np.array(labels)) X_train, X_test, y_train, y_test = train_test_split(padded_docs, labels, test_size=0.1, random_state=0) The following prints output this: print(X_train.shape) print(X_test.shape) print(y_train.shape) print(y_test.shape) (1647, 6204) (184, 6204) (1647, 8) (184, 8) I then prepare my model like this: e = Embedding(input_dim=vocab_size, weights=[embedding_matrix], input_length=max_length, output_dim=embedding_dim, trainable=False) print('Preparing the network') model = models.Sequential() model.add(e) model.add(layers.Flatten()) model.add(layers.Dense(units=100, input_dim=embedding_dim, activation='relu')) model.add(layers.Dense(len(labels), activation='softmax')) # compile the model model.compile(loss='binary_crossentropy', metrics=['acc']) # summarize the model print(model.summary()) # fit the model print('Fitting the model') model.fit(X_train, y_train, epochs=10, verbose=0, batch_size=500) # evaluate the model loss, accuracy = model.evaluate(X_test, y_test, verbose=0) print('Accuracy: %f' % (accuracy*100)) This outputs the following error: embedding_1 (Embedding) (None, 6204, 301) 47951106 _________________________________________________________________ flatten_1 (Flatten) (None, 1867404) 0 _________________________________________________________________ dense_1 (Dense) (None, 100) 186740500 _________________________________________________________________ dense_2 (Dense) (None, 1831) 184931 ================================================================= Total params: 234,876,537 Trainable params: 186,925,431 Non-trainable params: 47,951,106 _________________________________________________________________ None Fitting the model batch_size=batch_size) File "/Users/tim/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 789, in _standardize_user_data exception_prefix='target') File "/Users/tim/anaconda3/lib/python3.6/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data str(data_shape)) ValueError: Error when checking target: expected dense_2 to have shape (1831,) but got array with shape (8,) Process finished with exit code 1 Can someone point me in the right direction about how to go about fitting the dimensions of this model?
1
1
0
0
0
0
I want to find the number of unique tokens in a file. For this purpose I wrote the below code: splittedWords = open('output.txt', encoding='windows-1252').read().lower().split() uniqueValues = set(splittedWords) print(uniqueValues) The output.txt file is like this: Türkiye+Noun ,+Punc terörizm+Noun+Gen ve+Conj kitle+Noun imha+Noun silah+Noun+A3pl+P3sg+Gen küresel+Adj düzey+Noun+Loc olus+Verb+Caus+PastPart+P3sg tehdit+Noun+Gen boyut+Noun+P3sg karsi+Adj+P3sg+Loc ,+Punc tüm+Det ülke+Noun+A3pl+Gen yay+Verb+Pass+Inf2+Gen önle+Verb+Pass+Inf2+P3sg hedef+Noun+A3pl+P3sg+Acc paylas+Verb+PastPart+P3pl ,+Punc daha+Noun güven+Noun+With ve+Conj istikrar+Noun+With bir+Num dünya+Noun düzen+Noun+P3sg için+PostpPCGen birlik+Noun+Loc çaba+Noun göster+Verb+PastPart+P3pl bir+Num asama+Noun+Dat gel+Verb+Pass+Inf2+P3sg+Acc samimi+Adj ol+Verb+ByDoingSo arzula+Verb+Prog2+Cop .+Punc Ab+Noun ile+PostpPCNom gümrük+Noun Alan+Noun+P3sg+Loc+Rel kurumsal+Adj iliski+Noun+A3pl club+Noun toplanti+Noun+A3pl+P3sg Türkiye+Noun+Gen -+Punc At+Noun gümrük+Noun isbirlik+Noun+P3sg komite+Noun+P3sg ,+Punc Ankara+Noun Anlasma+Noun+P3sg+Gen 6+Num madde+Noun+P3sg uyar+Verb+When ortaklik+Noun rejim+Noun+P3sg+Gen uygula+Verb+Pass+Inf2+P3sg+Acc ve+Conj gelis+Verb+Inf2+P3sg+Acc sagla+Verb+Inf1 üzere+PostpPCNom ortaklik+Noun Konsey+Noun+P3sg+Gen 2+Num /+Punc 69+Num sayili+Adj karar+Noun+P3sg ile+Conj teknik+Noun komite+Noun mahiyet+Noun+P3sg+Loc kur+Verb+Pass+Narr+Cop .+Punc nispi+Adj nisbi+Adj görece+Adj+With izafi+Adj obur+Adj With this code I can get the unique tokens like Türkiye+Noun, Türkiye+Noun+Gen. But I want to get forexample Türkiye+Noun, Türkiye+Noun+Gen like only one token before the + sign. I only want Türkiye part. In the end Türkiye+Noun and Türkiye+Noun+Gen tokens needs to be same and only treated as a single unique token. I think I need to write regex for this purpose.
1
1
0
0
0
0
In Tfidf.fit_transform we are only using the parameters X and have not used y for fitting the data set. Is this right? We are generating the tfidf matrix for only parameters of the training set.We are not using ytrain in fitting the model. Then how do we make predictions for the test data set
1
1
0
0
0
0
I was trying to implement the value iteration algorithm. I have a grid grid = [[0, 0, 0, +1], [0, "W", 0, -1], [0, 0, 0, 0]] An actionlist actlist = {UP:1, DOWN:2, LEFT:3, RIGHT:4} And a reward function reward = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] I wrote a function T, which returns tuple of 3 tuples. def T(i,j,actions): if(i == 0 and j == 0): if(actions == UP): return (i,i,0.8),(i,i,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i+1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j,0.8),(i,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,i,0.1),(i+1,j,0.1) elif (i == 0 and j == 1): if(actions == UP): return (i,i,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i,j,0.1) elif(i == 0 and j == 2): if(actions == UP): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return(i+1,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i+1,j,0.1) elif(i == 0 and j == 3): if(actions == UP): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == DOWN): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == LEFT): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == RIGHT): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) # 2nd row elif (i == 1 and j == 0): if(actions == UP): return (i-1,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == DOWN): return (i+1,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == LEFT): return (i,j,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(i == 1 and j ==1): if(actions == UP): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == LEFT): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif (i == 1 and j == 2): if(actions == UP): return (i-1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i+1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(i == 1 and j == 3): if(actions == UP): return (-2,-2,0.8),(-2,-2,0.1),(-2,-2,0.1) elif(actions == DOWN): return (-2,-2,0.8),(-2,-2,0.1),(-2,-2,0.1) elif(actions == LEFT): return (-2,-2,0.8),(-2,-2,0.1),(-2,-2,0.1) elif(actions == RIGHT): return (-2,-2,0.8),(-2,-2,0.1),(-2,-2,0.1) # 3rd row elif(i == 2 and j == 0): if(actions == UP): return (i-1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j,0.1),(i,j+1,1,0.1) elif(actions == LEFT): return (i,j,0.8),(i-1,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i-1,j,0.1),(i,j,0.1) elif (i == 2 and j == 1): if(actions == UP): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i,j,0.1) elif(i == 2 and j == 2): if(actions == UP): return (i-1,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i-1,j,0.1),(i,j,1) elif(actions == RIGHT): return (i,j+1,0.8),(i-1,j,0.1),(i,j,0.1) elif(i == 2 and j == 3): if(actions == UP): return (i-1,j,0.8),(i,j-1,0.1),(i,j,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i-1,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j,0.8),(i-1,j,0.1),(i,j,0.1) This function is called in the value iteration function: def value_iteration(): U1 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] while True: U=U1.copy() delta = 0 for i in range(len(grid)): for j in range(len(grid[i])): U1[i][j] = max(sum(p*(R(k,l)+gamma*U[k][l]) for (k,l,p) in T(i,j,a)) for a in actlist) print(i,j,U1[i][j]) delta = max(delta, abs(U1[i][j] - U[i][j])) if delta <= epsilon*(1 - gamma)/gamma: return U The problem is, the first two iteration of the for loop went well with output 0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 But then the code stopped with the error ValueError: too many values to unpack (expected 3)
1
1
0
0
0
0
I want to do n-grams method but letter by letter Normal N-grams: sentence : He want to watch football match result: he, he want, want, want to , to , to watch , watch , watch football , football, football match, match I want to do this but letter by letter: word : Angela result: a, an, n , ng , g , ge, e ,el, l , la ,a This is my code using Sklearn , but it is still word-by-word not letter-by-letter: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(ngram_range=(1, 100),token_pattern = r"(?u)\b\w+\b") corpus = ['Angel','Angelica','John','Johnson'] X = vectorizer.fit_transform(corpus) analyze = vectorizer.build_analyzer() print(vectorizer.get_feature_names()) print(vectorizer.transform(['Angela']).toarray())
1
1
0
0
0
0
I have a data set like: Column1 Column2 a bc cdr cd r ab c bose beats bea ts bo se i phone sam sung samsung iphone If you notice both columns contains almost similar words, but are different in terms of format and have spaces in them. I want techniques such as Cosine Similarity or sequence matcher to match these to columns such that the results becomes like this: column 1 column 2 a bc ab c cd r cdr bose bo se bea ts beats i phone iphone samsung sam sung Please not, this is just a sample data, the strings are more complex than these. How can I leverage packages such as Cosine Similarity and Sequence Matcher to make this happen?
1
1
0
0
0
0
I am creating a system capable of tag a sentence based on a previous tagged sentences. I have a corpora with the structure as the Known Questions. Known Questions: city_name What are the most popular city in spain? amount_of_people How many people are in the city center? New questões: What are the most popular city in Italy? How many people are in the at the stadium? What is the nearest city to New York? Example of tags: city_name amount_of_people desired result: city_name What are the most popular city in Italy? amount_of_people How many people are in the at the stadium? city_name What is the nearest city to New York? I have in total 30 tags and 350 Senteces. is there any python framework or an known algorithm to analyze the corpora and tag a new sentence base on the corpora ?
1
1
0
0
0
0
I am trying an NLP technique to see similarity between words from two lists. The code is as below import en_core_web_sm nlp = en_core_web_sm.load() Listalpha = ['Apple', 'Grapes', 'Mango', 'Fig','Orange'] ListBeta = ['Carrot', 'Mango', 'Tomato', 'Potato', 'Lemon'] list_n =" ".join(ListBeta) doc = nlp(list_n) list_str = " ".join(Listalpha) doc2 = nlp(list_str) newlist = [] for token1 in doc: for token2 in doc2: newlist.append((token1.text, token2.text,token1.similarity(token2))) words_most_similar = sorted(newlist, key=lambda x: x[2], reverse=True) print(words_most_similar) I get the following output [('Mango', 'Mango', 1.0), ('Potato', 'Mango', 0.71168435), ('Lemon', 'Orange', 0.70560765), ('Carrot', 'Mango', 0.670182), ('Tomato', 'Mango', 0.6513121), ('Potato', 'Fig', 0.6306212), ('Tomato', 'Fig', 0.61672616), ('Carrot', 'Apple', 0.6077532), ('Lemon', 'Mango', 0.5978425), ('Mango', 'Fig', 0.5930651), ('Mango', 'Orange', 0.5529714), ('Potato', 'Apple', 0.5516073), ('Potato', 'Orange', 0.5486618), ('Lemon', 'Fig', 0.50294644), ('Mango', 'Apple', 0.48833746), ('Tomato', 'Orange', 0.44175738), ('Mango', 'Grapes', 0.42697987), ('Lemon', 'Apple', 0.42477235), ('Carrot', 'Fig', 0.3984716), ('Carrot', 'Grapes', 0.3944748), ('Potato', 'Grapes', 0.3860814), ('Tomato', 'Apple', 0.38342345), ('Carrot', 'Orange', 0.38251868), ('Tomato', 'Grapes', 0.3763761), ('Lemon', 'Grapes', 0.28998604)] How do I get an output in the format as below [('Mango','Mango',1.0),('Mango', 'Fig', 0.5930651), ('Mango', 'Orange', 0.5529714),('Mango', 'Apple', 0.48833746),('Mango', 'Grapes', 0.42697987),('Carrot', 'Mango', 0.670182),('Carrot', 'Apple', 0.6077532)....] Basically I want the mapping of the form (word in ListBeta, word in Listalpha, cosine score) and it should be uniform and not at random as I have currently. Also it needs to be in descending order of cosine value as depicted above.
1
1
0
0
0
0
My use case is to vectorize words in two lists like below. ListA = [Japan, Electronics, Manufacturing, Science] ListB = [China, Electronics, AI, Software, Science] I understand that word2vec and Glove can vectorize words but they do that through corpus or bag of words i.e we have to pass sentences which gets broken down to tokens and then it is vectorized. Is there a way to just vectorize words in a list? PS. I am new to NLP side of things, hence pardon any obvious points stated.
1
1
0
0
0
0
I'm trying TfidfVectorizer on a sentence taken from wikipedia page about the History of Portugal. However i noticed that the TfidfVec.fit_transform method is ignoring certain words. Here's the sentence i tried with: sentence = "The oldest human fossil is the skull discovered in the Cave of Aroeira in Almonda." TfidfVec = TfidfVectorizer() tfidf = TfidfVec.fit_transform([sentence]) cols = [words[idx] for idx in tfidf.indices] matrix = tfidf.todense() pd.DataFrame(matrix,columns = cols,index=["Tf-Idf"]) output of the dataframe: Essentially, it is ignoring the words "Aroeira" and "Almonda". But i don't want it to ignore those words so what should i do? I can't find anywhere on the documentation where they talk about this. Another question is why is the word "the" repeated? should the algorithm consider just one "the" and compute its tf-idf?
1
1
0
0
0
0
I used the gensim LDAModel for topic extraction for customer reviews as follows: dictionary = corpora.Dictionary(clean_reviews) dictionary.filter_extremes(keep_n=11000) #change filters dictionary.compactify() dictionary_path = "dictionary.dict" corpora.Dictionary.save(dictionary, dictionary_path) # convert tokenized documents to vectors corpus = [dictionary.doc2bow(doc) for doc in clean_reviews] vocab = lda.datasets.load_reuters_vocab() # Training lda using number of topics set = 10 (which can be changed) lda = gensim.models.LdaModel(corpus, id2word = dictionary, num_topics = 20, passes = 20, random_state=1, alpha = "auto") This returns unigrams in topics like: topic1 -delivery,parcel,location topic2 -app, login, access But I am looking for ngrams. I came across sklearn's LatentDirichletAllocation which uses Tfidf vectorizer as follows: vectorizer = TfidfVectorizer(analyzer='word', ngram_range=[2,5], stop_words='english', min_df=2) X = vectorizer.fit_transform(new_review_list) clf = decomposition.LatentDirichletAllocation(n_topics=20, random_state=3, doc_topic_prior = .1).fit(X) where we can specify range for ngrams in the vectorizer. Is it possible to do so in the gensim LDA Model as well. Sorry, I'm very new to using all these models, so don't know much about them.
1
1
0
0
0
0
I'm writing an algorithm in order to classify the tweets in my dataset as positive/negative and I want to test the accuracy of it. In order to do this and find the best possible solution I want to have a baseline (using classical ML algorithms). After preprocessing the tweets, inspired by the related work, I explored firstly with the Bag-of-Words model and I managed to successfully run the code and calculate the accuracy and the Fscore. After some text preprocessing and splitting the dataset into the train set and the test set: from sklearn.cross_validation import train_test_split X_train, X_test1, y_train, y_test1 = train_test_split(X, y, test_size = 0.11, random_state = 0) I want to be able to eliminate all the tweets labeled as negative from the test set (keeping only the positive ones) and calculate the precision, recall, and Fscore of the algorithm (and afterwards do the same thing for the tweets labeled as positive). I tried doing it like this: finRow = len(X_test1) finCol = len(X_test1[0]) for o in range(0, finrow): if y_test1[o]== 1: del y_test1[o] X_test1 = np.delete(X_test1, o, axis=0) but I get this error: Traceback (most recent call last): File "<ipython-input-4-5ed18876a8b5>", line 2, in <module> if y_test1[o]== 1: IndexError: list index out of range X_test1 contains the tweets and it's of size 1102 x 564 and y_test1 contains zeros and ones (the tweet is positive or negative) and has a size of 1102. The error appears at the 774th iteration, when the length of y_test1 decreases from 1102 to 774. Now, I tried doing it like this also: a = 1 for o in range(0, finrow): if (y_test1[o] == 1 and o <= finrow - a): del y_test1[o] a = a + 1 X_test1 = np.delete(X_test1, o, axis=0) but I still get the same error and I don't know if this is the best approach of deleting the rows of the matrix and the elements of the list because when I'm checking the values of y_test1 I still have some (a few, not all - as in the beginning) of the elements that were supposed to be deleted. I'm kind of new at this, and I have no idea where my mistake is.
1
1
0
0
0
0
Is there any limit to the number of training phrases I can use in Dialogflow? Because generally all other platforms have such limit
1
1
0
0
0
0
I am using gensim for some NLP task. I've created a corpus from dictionary.doc2bow where dictionary is an object of corpora.Dictionary. Now I want to filter out the terms with low tf-idf values before running an LDA model. I looked into the documentation of the corpus class but cannot find a way to access the terms. Any ideas? Thank you.
1
1
0
0
0
0
I want to grade/score the response of different users inputs. For this I have used Multinomial navie bayes. The below my code. # use natural language toolkit import nltk from nltk.stem.lancaster import LancasterStemmer import os import json import datetime stemmer = LancasterStemmer() # 3 classes of training data training_data = [] # capture unique stemmed words in the training corpus class_words={} corpus_words = {} classes = list(set([a['class'] for a in training_data])) for c in classes: class_words[c] = [] for data in training_data: # tokenize each sentence into words for word in nltk.word_tokenize(data['sentence']): # ignore a few things if word not in ["?", "'s"]: # stem and lowercase each word stemmed_word = stemmer.stem(word.lower()) if stemmed_word not in corpus_words: corpus_words[stemmed_word] = 1 else: corpus_words[stemmed_word] += 1 class_words[data['class']].extend([stemmed_word]) # we now have each word and the number of occurances of the word in our training corpus (the word's commonality) print ("Corpus words and counts: %s" % corpus_words) # also we have all words in each class print ("Class words: %s" % class_words) sentence="The biggest advantages to a JavaScript having a ability to support all modern browser and produce the same result." def calculate_class_score(sentence, class_name): score = 0 for word in nltk.word_tokenize(sentence): if word in class_words[class_name]: score += 1 return score for c in class_words.keys(): print ("Class: %s Score: %s" % (c, calculate_class_score(sentence, c))) # calculate a score for a given class taking into account word commonality def calculate_class_score_commonality(sentence, class_name): score = 0 for word in nltk.word_tokenize(sentence): if word in class_words[class_name]: score += (1 / corpus_words[word]) return score # now we can find the class with the highest score for c in class_words.keys(): print ("Class: %s Score: %s" % (c, calculate_class_score_commonality(sentence, c))) def find_class(sentence): high_class = None high_score = 0 for c in class_words.keys(): score = calculate_class_score_commonality(sentence, c) if score > high_score: high_class = c high_score = score return high_class, high_score Note: I haven't added any training data. When I give the input as find_class("the biggest advantages to a JavaScript having a ability to support all modern browser and produce the same result.JavaScript small bit of code you can test") I'm getting the output as ('Advantages', 5.07037037037037) But when I give the input as find_class("JavaScript can be executed within the user's browser without having to communicate with the server, saving on bandwidth") I'm getting the response/output as ('Advantages', 2.0454545) I'm building it for the JavaScript Interview/viva questions. When a user type the same answer in the different way as I mentioned above I'm getting I'm getting different scores. I want the scores to be precise. How can I do it.
1
1
0
1
0
0
I'm studying NLP and as example I'm trying to identify what feelings are in customer feedback in the online course platform. I was able to identify the feelings of the students with only simple sentence, such as "The course is very nice, I learned a lot from it", "The teaching platform is complete and I really enjoy using it", "I could have more courses related to marine biology", and so on. My doubt is how to correctly identify the various sentiments in one sentence or in several sentences. For example: A sentiment per sentence: "The course is very good! it could be cool to create a section of questions on the site." More than one sentiment per sentence: "The course is very good, but the site is not." Involving both: "The course is very good, but the teaching platform is very slow. There could be more tasks and examples in the courses, interaction by video or microphone on the forum, for example." I thought of splitting text in sentences, but it is not so good for the example 2.
1
1
0
0
0
0
I have this code here. import spacy nlp = spacy.load('en') a = set(nlp('This is a test')) b = nlp('is') if b in a: print("Success") else: print("Failed") for some reason this output printed out "Failed". I expected it to succeed. I am new in using the spacy framework so I'm not quite sure how to do this right. How do I do this right?
1
1
0
0
0
0
i computed tfidf vectorizer for text data and got vectors as (100000,2000) max_feature = 2000. while i am computing the co occurance matrix by below code. length = 2000 m = np.zeros([length,length]) # n is the count of all words def cal_occ(sentence,m): for i,word in enumerate(sentence): print(i) print(word) for j in range(max(i-window,0),min(i+window,length)): print(j) print(sentence[j]) m[word,sentence[j]]+=1 for sentence in tf_vec: cal_occ(sentence, m) I am getting the following error. 0 (0, 1210) 0.20426932204609685 (0, 191) 0.23516811545499153 (0, 592) 0.2537746177804585 (0, 1927) 0.2896119458034052 (0, 1200) 0.1624114163299802 (0, 1856) 0.24376566018277918 (0, 1325) 0.2789314085220367 (0, 756) 0.15365704375851477 (0, 1130) 0.293489555928974 (0, 346) 0.21231046306681553 (0, 557) 0.2036759579760878 (0, 1036) 0.29666992324872365 (0, 264) 0.36435609585838674 (0, 1701) 0.242619998334931 (0, 1939) 0.33934107208095693 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-96-ad505b6df734> in <module>() 11 m[word,sentence[j]]+=1 12 for sentence in tf_vec: ---> 13 cal_occ(sentence, m) <ipython-input-96-ad505b6df734> in cal_occ(sentence, m) 9 print(j) 10 print(sentence[j]) ---> 11 m[word,sentence[j]]+=1 12 for sentence in tf_vec: 13 cal_occ(sentence, m) IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
1
1
0
1
0
0
I was developing the n gram spell check as per the mentioned example . Although the algorithmic approach will be as follows: Consider 2 strings “statistics” and “statistical”. If n is set to 2 (bi-grams are being extracted), then the similarity of the two strings is calculated as follows: Initially, the two strings are split into bi-grams: Statistics - st ta at ti is st ti ic cs 9 bigrams Statistical - st ta at ti is st ti ic ca al 10 bigrams Then find the unique bi-grams in each string Statistics - st ta at is ti ic cs (7 unique bigrams) Statistical - st ta at ti is ic ca al (8 unique bigrams) Next, find the unique bi-grams that are shared with both the terms. There are 6 such bi-grams: st ta at ic is ti. The similarity measure is calculated using similarity coefficient with the following formula: Similarity coefficient = 2*C/A+B A - unique n-grams in term 1. B - unique n-grams in term 2. C - unique n-grams appearing in term 1 and term 2. The above example would produce the result (2*6) / (7+8) = 0.80. Higher the similarity measure is, more relevant is the word for correction. My sample output for the program looks like: Enter a word: ttem temp : 0.5 stem : 0.5 items : 0.4444444444444444 item : 0.5 How do i select the most probable candidate among them . i hope you can provide some sort of solutions to this. hope to see you guys.
1
1
0
0
0
0
here stem function shows error saying that stem required one positional argument in loop as in question? from nltk.stem import PorterStemmer as ps text='my name is pythonly and looking for a pythonian group to be formed by me iteratively' words = word_tokenize(text) for word in words: print(ps.stem(word))
1
1
0
0
0
0
I am using Keras to capture semantic information for a dataset. And I already tokenize the data to integer vectors. It has a form like this: texts=[[1,2,3,2,1], [2,3,4,2,2], [3,33,2,1,3]] labels=[1,0,1] And the labels only contains 0 or 1, each list contain one label. I want to use Keras's embedding layer to embed this. But the examples on the Internet only contain a list: texts=[1,2,3,4,2,1] I am wondering can I input a matrix to the embedding layer?
1
1
0
1
0
0
I am trying to classify email as spam/ham using NLTK Below are the steps followed : Trying to extract all the tokens Fetching all the features Extracting features from the corpus of all unique words and mapping True/false Training the data in Naive Bayes classifier from nltk.classify.util import apply_features from nltk import NaiveBayesClassifier import pandas as pd import collections from sklearn.model_selection import train_test_split from collections import Counter data = pd.read_csv('https://raw.githubusercontent.com/venkat1017/Data/master/emails.csv') """fetch array of tuples where each tuple is defined by (tokenized_text, label) """ processed_tokens=data['text'].apply(lambda x:([x for x in x.split() if x.isalpha()])) processed_tokens=processed_tokens.apply(lambda x:([x for x in x if len(x)>3])) processed_tokens = [(i,j) for i,j in zip(processed_tokens,data['spam'])] """ dictword return a Set of unique words in complete corpus. """ list = zip(*processed_tokens) dictionary = Counter(word for i, j in processed_tokens for word in i) dictword = [word for word, count in dictionary.items() if count == 1] """maps each input text into feature vector""" y_dict = ( [ (word, True) for word in dictword] ) feature_vec=dict(y_dict) """Training""" training_set, testing_set = train_test_split(y_dict, train_size=0.7) classifier = NaiveBayesClassifier.train(training_set) ~\AppData\Local\Continuum\anaconda3\lib\site-packages ltk\classify aivebayes.py in train(cls, labeled_featuresets, estimator) 197 for featureset, label in labeled_featuresets: 198 label_freqdist[label] += 1 --> 199 for fname, fval in featureset.items(): 200 # Increment freq(fval|label, fname) 201 feature_freqdist[label, fname][fval] += 1 AttributeError: 'str' object has no attribute 'items' I am facing with the following error when trying to train the corpus of unique words
1
1
0
1
0
0
When running the below code. this Python 3.6, latest Gensim library in Jupyter for model in models: print(str(model)) pprint(model.docvecs.most_similar(positive=["Machine learning"], topn=20)) [1]: https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-wikipedia.ipynb
1
1
0
0
0
0
I am trying to concatenate the hidden units. For example, I have 3 units, h1,h2,h3 then I want the new layer to have [h1;h1],[h1;h2],[h1;h3],[h2;h1].... So, I have tried: class MyLayer(Layer): def __init__(self,W_regularizer=None,W_constraint=None, **kwargs): self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.W_constraint = constraints.get(W_constraint) super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 # Create a trainable weight variable for this layer. self.W = self.add_weight((input_shape[-1],input_shape[-1]), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint, trainable=True) super(MyLayer, self).build(input_shape) def call(self, x,input_shape): conc=K.concatenate([x[:, :-1, :], x[:, 1:, :]],axis=1)# help needed here uit = K.dot(conc, self.W)# W has input_shape[-1],input_shape[-1] return uit def compute_output_shape(self, input_shape): return input_shape[0], input_shape[1],input_shape[-1] I am not sure what should I return for the second argument of my output shape. from keras.layers import Input, Lambda, LSTM from keras.models import Model import keras.backend as K from keras.layers import Lambda lstm=LSTM(64, return_sequences=True)(input) something=MyLayer()(lstm)
1
1
0
0
0
0
How can I get the term frequency(TF) of every term in the vocabulary created by sklearn.feature_extraction.text.CountVectorizer and put them into a list or a dict? It seems that all values corresponding to keys in the vocabulary are int numbers smaller than max_features which I set manually when initializing the CountVectorizer, rather than TF——it should be a float number. Can anyone give me a help? CV=CountVectorizer(ngram_range(ngram_min_file_opcode,ngram_max_file_opcode), decode_error="ignore", max_features=max_features_file_re, token_pattern=r'\b\w+\b', min_df=1, max_df=1.0) x = CV.fit_transform(x).toarray()
1
1
0
1
0
0
given a corpus and test set. corpus contains 10000 complete sentences. The test set contains 100 incomplete sentence,where each sentence has 3 consecutive words. I want to train the corpus using ngrams and predict the next word for the Test Set. text = 'dataset.txt' # Order of the grams n = 2 ngrams = {} words = nltk.word_tokenize(text) for i in range(len(words)-n): gram = ' '.join(words[i:i+n]) if gram not in ngrams.keys(): ngrams[gram] = [] ngrams[gram].append(words[i+n]) currentGram = ' '.join(words[0:n]) result = currentGram for i in range(30): if currentGram not in ngrams.keys(): break possibilities = ngrams[currentGram] nextItem = possibilities[random.randrange(len(possibilities))] result += ' '+nextItem rWords = nltk.word_tokenize(result) currentGram = ' '.join(rWords[len(rWords)-n:len(rWords)]) test set is in .csv format Top five lines of a test set
1
1
0
1
0
0
I have dataframe with two text fields and other features like this format : message feature_1 feature_2 score text 'This is the text' 4 7 10 extra text 'This is more text' 3 2 8 and this is another text Now my goal is to predict the score, when trying to transform this dataframe into a feature matrix to feed it into my machine learning model, here is what I have did : # Create vectorizer for function to use vectorizer = TfidfVectorizer() # combine the numerical features with the TFIDF generated matrix X = sp.sparse.hstack( (vectorizer.fit_transform(df.message), df[['feature_1', 'feature_2']].values, vectorizer.fit_transform(df.text)), format='csr') Now when printing the shape of my X matrix I got 2x13, but when I check the X_columsn like this : X_columns = vectorizer.get_feature_names() + df[['feature_1', 'feature_2']].columns.tolist() I don't get all the words in the corpus, it bring me just the words existing in df.text and other features attribute without words in df.message . ['and', 'another', 'extra', 'is', 'text', 'this', 'feature_1', 'feature_2'] How can I make X contain all my dataframe features !!
1
1
0
0
0
0
I am having trouble converting a fast FastText vector back to a word. Here is my python code: from gensim.models import KeyedVectors en_model = KeyedVectors.load_word2vec_format('wiki.en/wiki.en.vec') vect = en_model.get_vector("turtles") How can I take the vector (especially an arbitrary vector with the proper dimensions) and have it spit out a word?
1
1
0
0
0
0
I am working on an NLP project that analyzes specifications in natural language. I am using NLTK toolkit and autocorrect for tokenizing, POS tagging and checking for misspelling. But I run into a problem recently. So the example is "Then it terns left." while the user actually means "Then it turns left." The POS tagger from the NLTK toolkit recognizes the "terns" as an Adjective. But since the sentence itself is grammatically incorrect and NLTK parser is still limited to corrected sentences, I won't blame it. And since "tern" is a correct English word, the autocorrect function also doesn't catch the error. When I use grammar tools like Grammarly to test the sentence, it gives me suggestion like: the word "terns" does not seem to fit this context, and suggest me to replace it with "turns". How can I fix this problem? For example, report the error and give suggestion on the sentence "Then it terns left." --> "Then it turns left." My thought now is to check the grammar first. For example, maybe to say the word between "it" and "left" should be a verb. Then gives the suggestion based on the fact that we need a verb. The NLTK parser doesn't really tell which word cause the problem. I also tried grammar-check and language-check (which they are the same). It is too slow for my purpose. Any suggestion on how to solve this problem?
1
1
0
0
0
0
I have a paragraph and would like to compute the co-occurrence matrix of words given a fixed window size. a='Apply singular value decomposition to obtain word embeddings and compare with word2vec'.split() list(skipgrams(a,n=2,k=4)) Output is a list of tuples [('Apply', 'singular'), ('Apply', 'value'), ('Apply', 'decomposition'),...] How can I use this skipgram result to convert to co-occurrence matrix? Is there any existing functions or libraries I can use? (i.e. not create zero matrix and for loop each tuple). Seems countvectorizer is for ngrams..
1
1
0
1
0
0
I have a list of words and would like to keep only nouns. This is not a duplicate of Extracting all Nouns from a text file using nltk In the linked question a piece of text is processed. The accepted answer proposes a tagger. I'm aware of the different options for tagging text (nlkt, textblob, spacy), but I can't use them, since my data doesn't consist of sentences. I only have a list of individual words: would research part technologies size articles analyzes line nltk has a wide selection of corpora. I found verbnet with a comprehensive list of verbs. But so far I didn't see anything similar for nouns. Is there something like a dictionary, where I can look up if a word is a noun, verb, adjective, etc ? This could probably done by some online service. Microsoft translate for example returns a lot of information in their responses: https://learn.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup?tabs=curl But this is a paid service. I would prefer a python package. Regarding the ambiguity of words: Ideally I would like a dictionary that can tell me all the functions a word can have. "fish" for example is both noun and verb. "eat" is only verb, "dog" is only noun. I'm aware that this is not an exact science. A working solution would simply remove all words that can't be nouns.
1
1
0
0
0
0