NLP interview questions
52 questions with answers. 404 open jobs in India ask for NLP.
How can we use machine learning for text classification?Intermediate
Machine learning classification algorithms predict a class based on a numerical feature representation. This means that in order to use machine learning for text classification, we need to extract numerical features from our text data first before we can apply machine learning algorithms. Common approaches to extract numerical features from text data are bag of words, N-grams or word embeddings.
From Data Science Interviews (CC BY 4.0)
What is bag of words? How we can use it for text classification?Intermediate
Bag of Words is a representation of text that describes the occurrence of words within a document. The order or structure of the words is not considered. For text classification, we look at the histogram of the words within the text and consider each word count as a feature.
From Data Science Interviews (CC BY 4.0)
What are the advantages and disadvantages of bag of words?Intermediate
Advantages:
- Simple to understand and implement.
Disadvantages:
- The vocabulary requires careful design, most specifically in order to manage the size, which impacts the sparsity of the document representations.
- Sparse representations are harder to model both for computational reasons (space and time complexity) and also for information reasons
- Discarding word order ignores the context, and in turn meaning of words in the document. Context and meaning can offer a lot to the model, that if modeled could tell the difference between the same words differently arranged (“this is interesting” vs “is this interesting”), synonyms (“old bike” vs “used bike”).
From Data Science Interviews (CC BY 4.0)
What are N-grams? How can we use them?Intermediate
The function to tokenize into consecutive sequences of words is called n-grams. It can be used to find out N most co-occurring words (how often word X is followed by word Y) in a given sentence.
From Data Science Interviews (CC BY 4.0)
What is TF-IDF? How is it useful for text classification?Intermediate
Term Frequency (TF) is a scoring of the frequency of the word in the current document. Inverse Document Frequency(IDF) is a scoring of how rare the word is across documents. It is used in scenario where highly recurring words may not contain as much informational content as the domain specific words. For example, words like “the” that are frequent across all documents therefore need to be less weighted. The TF-IDF score highlights words that are distinct (contain useful information) in a given document.
From Data Science Interviews (CC BY 4.0)
Which model would you use for text classification with bag of words features?Intermediate
- Bag Of Words model
- Word2Vec Embeddings
- fastText Embeddings
- Convolutional Neural Networks (CNN)
- Long Short-Term Memory (LSTM)
- Bidirectional Encoder Representations from Transformers (BERT)
From Data Science Interviews (CC BY 4.0)
Would you prefer gradient boosting trees model or logistic regression when doing text classification with bag of words?Intermediate
Usually logistic regression is better because bag of words creates a matrix with large number of columns. For a huge number of columns logistic regression is usually faster than gradient boosting trees.
From Data Science Interviews (CC BY 4.0)
What are word embeddings? Why are they useful? Do you know Word2Vec?Intermediate
Word Embeddings are vector representations for words. Each word is mapped to one vector, this vector tries to capture some characteristics of the word, allowing similar words to have similar vector representations.
Word Embeddings helps in capturing the inter-word semantics and represents it in real-valued vectors.Word2Vec is a method to construct such an embedding. It takes a text corpus as input and outputs a set of vectors which represents words in that corpus.
It can be generated using two methods:
- Common Bag of Words (CBOW)
- Skip-Gram
From Data Science Interviews (CC BY 4.0)
If you have a sentence with multiple words, you may need to combine multiple word embeddings into one. How would you do it?Intermediate
Approaches ranked from simple to more complex:
- Take an average over all words
- Take a weighted average over all words. Weighting can be done by inverse document frequency (idf part of tf-idf).
- Use ML model like LSTM or Transformer.
From Data Science Interviews (CC BY 4.0)
Would you prefer gradient boosting trees model or logistic regression when doing text classification with embeddings?Intermediate
Gradient boosting trees (GBTs) are generally a better choice than logistic regression for text classification with embeddings. This is because GBTs are able to learn more complex relationships between the features in the data, including the features extracted from the embeddings.
Logistic regression is a linear model, which means that it can only learn linear relationships between the features. This can be a limitation for text classification, where the relationships between the features are often complex and non-linear.
GBTs, on the other hand, are able to learn non-linear relationships between the features by combining multiple decision trees. This allows GBTs to learn more complex patterns in the data, which can lead to better performance on text classification tasks.
In addition, GBTs are more robust to outliers and noise in the data than logistic regression. This can be important for text classification tasks, where the data can be noisy and imbalanced.
Overall, GBTs are a better choice than logistic regression for text classification with embeddings, especially when the data is noisy or imbalanced. However, it is important to consider the computational cost and interpretability of GBTs before using them.
From Data Science Interviews (CC BY 4.0)
How can you use neural nets for text classification?Advanced
Here is a general overview of how to use neural nets for text classification:
Preprocess the text: This includes cleaning the text by removing stop words, punctuation, and other irrelevant symbols. It may also involve converting the text to lowercase and stemming or lemmatizing the words. Represent the text as a vector: This can be done using a variety of methods, such as one-hot encoding or word embeddings. Build the neural net: The neural net architecture will depend on the specific text classification task. However, a typical architecture will include an embedding layer, one or more hidden layers, and an output layer. Train the neural net: The neural net is trained by feeding it labeled examples of text data. The neural net will learn to adjust its parameters in order to minimize the loss function, which is typically the cross-entropy loss function. Evaluate the neural net: Once the neural net is trained, it can be evaluated on a held-out test set to assess its performance. Here are some specific examples of how neural nets can be used for text classification: Sentiment analysis, Spam detection, Topic classification, Language identification
Neural nets have achieved state-of-the-art results on many text classification tasks. However, they can be computationally expensive to train and deploy.
From Data Science Interviews (CC BY 4.0)
How can we use CNN for text classification?Advanced
Here are some specific examples of how CNNs can be used for text classification:
Sentiment analysis: CNNs can be used to classify text as positive, negative, or neutral sentiment. This is a common task in social media analysis and customer service. Spam detection: CNNs can be used to classify emails as spam or not spam. This is a common task in email filtering systems. Topic classification: CNNs can be used to classify text documents into different topics. This is a common task in news and social media analysis. Language identification: CNNs can be used to identify the language of a text document. This is a common task in translation systems.
From Data Science Interviews (CC BY 4.0)
What is the difference between lemmatization vs stemming?
Short and dense: http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html
The goal of both stemming and lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form.
However, the two words differ in their flavor. Stemming usually refers to a crude heuristic process that chops off the ends of words in the hope of achieving this goal correctly most of the time, and often includes the removal of derivational affixes. Lemmatization usually refers to doing things properly with the use of a vocabulary and morphological analysis of words, normally aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma .
From the NLTK docs:
Lemmatization and stemming are special cases of normalization. They identify a canonical representative for a set of related word forms.
From Stack Overflow: asked by TIMEX, answered by miku (CC BY-SA 4.0)
Understanding min_df and max_df in scikit CountVectorizer
max_dfis used for removing terms that appear too frequently, also known as "corpus-specific stop words". For example:max_df = 0.50means "ignore terms that appear in more than 50% of the documents".max_df = 25means "ignore terms that appear in more than 25 documents".
The default
max_dfis1.0, which means "ignore terms that appear in more than 100% of the documents". Thus, the default setting does not ignore any terms.min_dfis used for removing terms that appear too infrequently. For example:min_df = 0.01means "ignore terms that appear in less than 1% of the documents".min_df = 5means "ignore terms that appear in less than 5 documents".
The default
min_dfis1, which means "ignore terms that appear in less than 1 document". Thus, the default setting does not ignore any terms.From Stack Overflow: asked by moeabdol, answered by Kevin Markham (CC BY-SA 3.0)
Difference between constituency parser and dependency parser
A constituency parse tree breaks a text into sub-phrases. Non-terminals in the tree are types of phrases, the terminals are the words in the sentence, and the edges are unlabeled. For a simple sentence "John sees Bill", a constituency parse would be:
Sentence | +-------------+------------+ | | Noun Phrase Verb Phrase | | John +-------+--------+ | | Verb Noun Phrase | | sees BillA dependency parse connects words according to their relationships. Each vertex in the tree represents a word, child nodes are words that are dependent on the parent, and edges are labeled by the relationship. A dependency parse of "John sees Bill", would be:
sees | +--------------+ subject | | object | | John BillYou should use the parser type that gets you closest to your goal. If you are interested in sub-phrases within the sentence, you probably want the constituency parse. If you are interested in the dependency relationships between words, then you probably want the dependency parse.
The Stanford parser can give you either (online demo). In fact, the way it really works is to always parse the sentence with the constituency parser, and then, if needed, it performs a deterministic (rule-based) transformation on the constituency parse tree to convert it into a dependency tree.
More can be found here:
From Stack Overflow: asked by RAVI, answered by dhg (CC BY-SA 4.0)
What is the concept of negative-sampling in word2vec?
The idea of
word2vecis to maximise the similarity (dot product) between the vectors for words which appear close together (in the context of each other) in text, and minimise the similarity of words that do not. In equation (3) of the paper you link to, ignore the exponentiation for a moment. You havev_c . v_w ------------------- sum_i(v_ci . v_w)The numerator is basically the similarity between words
c(the context) andw(the target) word. The denominator computes the similarity of all other contextsciand the target wordw. Maximising this ratio ensures words that appear closer together in text have more similar vectors than words that do not. However, computing this can be very slow, because there are many contextsci. Negative sampling is one of the ways of addressing this problem- just select a couple of contextsciat random. The end result is that ifcatappears in the context offood, then the vector offoodis more similar to the vector ofcat(as measures by their dot product) than the vectors of several other randomly chosen words (e.g.democracy,greed,Freddy), instead of all other words in language. This makesword2vecmuch much faster to train.From Stack Overflow: asked by Andy K, answered by mbatchkarov (CC BY-SA 4.0)
What does Keras Tokenizer method exactly do?
From the source code:
fit_on_textsUpdates internal vocabulary based on a list of texts. This method creates the vocabulary index based on word frequency. So if you give it something like, "The cat sat on the mat." It will create a dictionary s.t.word_index["the"] = 1; word_index["cat"] = 2it is word -> index dictionary so every word gets a unique integer value. 0 is reserved for padding. So lower integer means more frequent word (often the first few are stop words because they appear a lot).texts_to_sequencesTransforms each text in texts to a sequence of integers. So it basically takes each word in the text and replaces it with its corresponding integer value from theword_indexdictionary. Nothing more, nothing less, certainly no magic involved.
Why don't combine them? Because you almost always fit once and convert to sequences many times. You will fit on your training corpus once and use that exact same
word_indexdictionary at train / eval / testing / prediction time to convert actual text into sequences to feed them to the network. So it makes sense to keep those methods separate.From Stack Overflow: asked by Jack Fleeting, answered by nuric (CC BY-SA 4.0)
Is there a good natural language processing library
LingPipe is very nice and well documented. You can also take a look at:
The last one specifically might be of interest to you, although I don't know whether there are any readily available Java implementations (and maybe that's too big of a gun for your problem anyway :-)
Paul's idea of using a DSL is probably easier and faster to implement, and more reliable to use for your customers. I, too, would recommend looking into that first.
From Stack Overflow: asked by Vini, answered by n3rd (CC BY-SA 4.0)
Stemmers vs Lemmatizers
Q1: "[..] are English stemmers any useful at all today? Since we have a plethora of lemmatization tools for English"
Yes. Stemmers are much simpler, smaller, and usually faster than lemmatizers, and for many applications, their results are good enough. Using a lemmatizer for that is a waste of resources. Consider, for example, dimensionality reduction in Information Retrieval. You replace all drive/driving with driv in both the searched documents and the query. You do not care if it is drive or driv or x17a$ as long as it clusters inflectionally related words together.
Q2: "[..]how should we move on to build robust lemmatizers that can take on nounify, verbify, adjectify, and adverbify preprocesses?
What is your definition of a lemma, does it include derivation (drive - driver) or only inflection (drive - drives - drove)? Does it take into account semantics?
If you want to include derivation (which most people would say includes verbing nouns etc.) then keep in mind that derivation is far more irregular than inflection. There are many idiosyncracies, gaps, etc. Do you really want for to change (change trains) and change (as coins) to have the same lemma? If not, where do you draw the boundary? How about nerve - unnerve, earth -- unearth - earthling, ... It really depends on the application.
If you take into account semantics (bank would be labeled as bank-money or bank-river depending on context), how deep do you go (do you distinguish bank-institution from bank-building)? Some apps may not care about this at all, some might want to distinguish basic semantics, and some might want it fined-grained.
Q3: "How could the lemmatization task be easily scaled to other languages that have similar morphological structures as English?"
What do you mean by "similar morphological structures as English"? English has very little inflectional morphology. There are good lemmatizers for languages of other morphological types (truly inflectional, agglutinative, template, ...).
With a possible exception of agglutinative languages, I would argue that a lookup table (say a compressed trie) is the best solution. (Possibly with some backup rules for unknown words such as proper names). The lookup is followed by some kind of disambiguation (ranging from trivial - take the first one, or take the first one consistent with the words POS tag, to much more sophisticated). The more sophisticated disambiguations are usually supervised stochastical algorithms (e.g. TreeTagger or Faster), although a combination of machine learning and manually created rules has been done too (see e.g. this).
Obviously, for most languages, you do not want to create the lookup table by hand, but instead, generate it from a description of the morphology of that language. For inflectional languages, you can go the engineering way of Hajic for Czech or Mikheev for Russian, or, if you are daring, you use two-level morphology. Or you can do something in between, such as Hana (myself) (Note that these are all full morphological analyzers that include lemmatization as one of their features). Or you can learn the lemmatizer in an unsupervised manner a la Yarowsky and Wicentowski, possibly with manual post-processing, correcting the most frequent words.
There are way too many options and it really all depends on what you want to do with the results.
From Stack Overflow: asked by alvas, answered by Jirka (CC BY-SA 4.0)
What do spaCy's part-of-speech and dependency tags mean?
tl;dr answer
Just expand the lists at:
- https://spacy.io/api/annotation#pos-tagging (POS tags) and
- https://spacy.io/api/annotation#dependency-parsing (dependency tags)
Longer answer
The docs have greatly improved since I first asked this question, and spaCy now documents this much better.
Part-of-speech tags
The
posandtagattributes are tabulated at https://spacy.io/api/annotation#pos-tagging, and the origin of those lists of values is described. At the time of this (January 2020) edit, the docs say of theposattribute that:spaCy maps all language-specific part-of-speech tags to a small, fixed set of word type tags following the Universal Dependencies scheme. The universal tags don’t code for any morphological features and only cover the word type. They’re available as the
Token.posandToken.pos_attributes.As for the
tagattribute, the docs say:The English part-of-speech tagger uses the OntoNotes 5 version of the Penn Treebank tag set. We also map the tags to the simpler Universal Dependencies v2 POS tag set.
and
The German part-of-speech tagger uses the TIGER Treebank annotation scheme. We also map the tags to the simpler Universal Dependencies v2 POS tag set.
You thus have a choice between using a coarse-grained tag set that is consistent across languages (
.pos), or a fine-grained tag set (.tag) that is specific to a particular treebank, and hence a particular language..pos_tag listThe docs list the following coarse-grained tags used for the
posandpos_attributes:ADJ: adjective, e.g. big, old, green, incomprehensible, firstADP: adposition, e.g. in, to, duringADV: adverb, e.g. very, tomorrow, down, where, thereAUX: auxiliary, e.g. is, has (done), will (do), should (do)CONJ: conjunction, e.g. and, or, butCCONJ: coordinating conjunction, e.g. and, or, butDET: determiner, e.g. a, an, theINTJ: interjection, e.g. psst, ouch, bravo, helloNOUN: noun, e.g. girl, cat, tree, air, beautyNUM: numeral, e.g. 1, 2017, one, seventy-seven, IV, MMXIVPART: particle, e.g. ’s, not,PRON: pronoun, e.g I, you, he, she, myself, themselves, somebodyPROPN: proper noun, e.g. Mary, John, London, NATO, HBOPUNCT: punctuation, e.g. ., (, ), ?SCONJ: subordinating conjunction, e.g. if, while, thatSYM: symbol, e.g. $, %, §, ©, +, −, ×, ÷, =, :), 😝VERB: verb, e.g. run, runs, running, eat, ate, eatingX: other, e.g. sfpksdpsxmsaSPACE: space, e.g.
Note that the docs are lying slightly when they say that this list follows the Universal Dependencies Scheme; there are two tags listed above that aren't part of that scheme.
Read the rest at the sourceFrom Stack Overflow: asked by Mark Amery, answered by Mark Amery (CC BY-SA 4.0)
What are the major differences and benefits of Porter and Lancaster Stemming algorithms?
At the very basics of it, the major difference between the porter and lancaster stemming algorithms is that the lancaster stemmer is significantly more aggressive than the porter stemmer. The three major stemming algorithms in use today are Porter, Snowball(Porter2), and Lancaster (Paice-Husk), with the aggressiveness continuum basically following along those same lines. Porter is the least aggressive algorithm, with the specifics of each algorithm actually being fairly lengthy and technical. Here is a break down for you though:
Porter: Most commonly used stemmer without a doubt, also one of the most gentle stemmers. One of the few stemmers that actually has Java support which is a plus, though it is also the most computationally intensive of the algorithms(Granted not by a very significant margin). It is also the oldest stemming algorithm by a large margin.
Porter2: Nearly universally regarded as an improvement over porter, and for good reason. Porter himself in fact admits that it is better than his original algorithm. Slightly faster computation time than porter, with a fairly large community around it.
Lancaster: Very aggressive stemming algorithm, sometimes to a fault. With porter and snowball, the stemmed representations are usually fairly intuitive to a reader, not so with Lancaster, as many shorter words will become totally obfuscated. The fastest algorithm here, and will reduce your working set of words hugely, but if you want more distinction, not the tool you would want.
Honestly, I feel that Snowball is usually the way to go. There are certain circumstances in which Lancaster will hugely trim down your working set, which can be very useful, however the marginal speed increase over snowball in my opinion is not worth the lack of precision. Porter has the most implementations though and so is usually the default go-to algorithm, but if you can, use snowball.
Snowball - Additional info
Snowball is a small string processing language designed for creating stemming algorithms for use in Information Retrieval.
The Snowball compiler translates a Snowball script into another language - currently ISO C, C#, Go, Java, Javascript, Object Pascal, Python and Rust are supported.
History of the name
Since it effectively provides a ‘suffix STRIPPER GRAMmar’, I had toyed with the idea of calling it ‘strippergram’, but good sense has prevailed, and so it is ‘Snowball’ named as a tribute to SNOBOL, the excellent string handling language of Messrs Farber, Griswold, Poage and Polonsky from the 1960s.
---Martin PorterStemmers implemented in the Snowball language are sometimes simply referred to as Snowball stemmers. For example, see the Natural Language Toolkit: nltk.stem.snowball.
From Stack Overflow: asked by Adam Hess, answered by Slater Victoroff (CC BY-SA 4.0)
What is a projection layer in the context of neural networks?
I find the previous answers here a bit overcomplicated - a projection layer is just a simple matrix multiplication, or in the context of NN, a regular/dense/linear layer, without the non-linear activation in the end (sigmoid/tanh/relu/etc.) The idea is to project the (e.g.) 100K-dimensions discrete vector into a 600-dimensions continuous vector (I chose the numbers here randomly, "your mileage may vary"). The exact matrix parameters are learned through the training process.
What happens before/after already depends on the model and context, and is not what OP asks.
(In practice you wouldn't even bother with the matrix multiplication (as you are multiplying a 1-hot vector which has 1 for the word index and 0's everywhere else), and would treat the trained matrix as a lookout table (i.e. the 6257th word in the corpus = the 6257th row/column (depends how you define it) in the projection matrix).)
From Stack Overflow: asked by Roger, answered by Maverick Meerkat (CC BY-SA 4.0)
What is CoNLL data format?
There are many different CoNLL formats since CoNLL is a different shared task each year. The format for CoNLL 2009 is described here. Each line represents a single word with a series of tab-separated fields.
_s indicate empty values. Mate-Parser's manual says that it uses the first 12 columns of CoNLL 2009:ID FORM LEMMA PLEMMA POS PPOS FEAT PFEAT HEAD PHEAD DEPREL PDEPRELThe definition of some of these columns come from earlier shared tasks (the CoNLL-X format used in 2006 and 2007):
ID(index in sentence, starting at 1)FORM(word form itself)LEMMA(word's lemma or stem)POS(part of speech)FEAT(list of morphological features separated by |)HEAD(index of syntactic parent, 0 forROOT)DEPREL(syntactic relationship betweenHEADand this word)
There are variants of those columns (e.g.,
PPOSbut notPOS) that start withPindicate that the value was automatically predicted rather a gold standard value.Update: There is now a CoNLL-U data format as well which extends the CoNLL-X format.
From Stack Overflow: asked by swapna sourav rout, answered by dmcc (CC BY-SA 4.0)
Is there an algorithm that tells the semantic similarity of two phrases
You might want to check out this paper:
Sentence similarity based on semantic nets and corpus statistics (PDF)
I've implemented the algorithm described. Our context was very general (effectively any two English sentences) and we found the approach taken was too slow and the results, while promising, not good enough (or likely to be so without considerable, extra, effort).
You don't give a lot of context so I can't necessarily recommend this but reading the paper could be useful for you in understanding how to tackle the problem.
Regards,
Matt.
From Stack Overflow: asked by btw0, answered by Matt Mower (CC BY-SA 3.0)
What programming language is most like natural language?
There is a programming language called Inform that, in its most recent incarnation, Inform 7, looks a lot like natural language...in particular, written language.
Inform is very specifically for creating text adventure games, but there is no inherent reason that the concepts couldn't be extended into other realms.
Here's a small snippet of Inform 7 code, taken from the game Glass, by Emily Short.
Stage is a room. The old lady is a woman in the Stage. Understand "mother" or "stepmother" as the old lady. The old lady is active. The description of the lady is "She looks plucked: thin neck with folds of skin exposed, nose beaky, lips white. Perhaps when her fortunes are mended her cosmetics too will improve." The Prince is a man in the Stage. The description of the prince is "He's tolerably attractive, in his flightless way. It's hard not to pity him a little." The prince carries a glass slipper. The glass slipper is wearable. Understand "shoe" or "heel" or "toe" or "foot" as the slipper. The description of the slipper is "It is very small for an adult woman's foot."Complete code can be found here.
This is a small simple example...it can actually handle a surprisingly robust set of ideas.
It should be pointed out that the code isn't really a strange cypher where the constructs have hidden meanings...this code does more or less what you would expect. For example:
The old lady is a woman in the Stage. Understand "mother" or "stepmother" as the old lady.creates an object that happens to be a female person, names that object "old lady", and places that object within the room object called the "Stage". Then two aliases ("mother" and "stepmother" are created that also both reference the "old lady" object.
Of course, as the examples get increasingly complex, the necessary hoops to jump through also become more complex. English is, by its very nature, ambiguous, while computer code is most definitively not. So we'll never get a "perfect marriage".
From Stack Overflow: asked by kliketa, answered by Beska (CC BY-SA 2.5)
Text Summarization Evaluation - BLEU vs ROUGE
In general:
Bleu measures precision: how much the words (and/or n-grams) in the machine generated summaries appeared in the human reference summaries.
Rouge measures recall: how much the words (and/or n-grams) in the human reference summaries appeared in the machine generated summaries.
Naturally - these results are complementing, as is often the case in precision vs recall. If you have many words from the system results appearing in the human references you will have high Bleu, and if you have many words from the human references appearing in the system results you will have high Rouge.
In your case it would appear that sys1 has a higher Rouge than sys2 since the results in sys1 consistently had more words from the human references appear in them than the results from sys2. However, since your Bleu score showed that sys1 has lower recall than sys2, this would suggest that not so many words from your sys1 results appeared in the human references, in respect to sys2.
This could happen for example if your sys1 is outputting results which contain words from the references (upping the Rouge), but also many words which the references didn't include (lowering the Bleu). sys2, as it seems, is giving results for which most words outputted do appear in the human references (upping the Blue), but also missing many words from its results which do appear in the human references.
BTW, there's something called brevity penalty, which is quite important and has already been added to standard Bleu implementations. It penalizes system results which are shorter than the general length of a reference (read more about it here). This complements the n-gram metric behavior which in effect penalizes longer than reference results, since the denominator grows the longer the system result is.
You could also implement something similar for Rouge, but this time penalizing system results which are longer than the general reference length, which would otherwise enable them to obtain artificially higher Rouge scores (since the longer the result, the higher the chance you would hit some word appearing in the references). In Rouge we divide by the length of the human references, so we would need an additional penalty for longer system results which could artificially raise their Rouge score.
Finally, you could use the F1 measure to make the metrics work together: F1 = 2 * (Bleu * Rouge) / (Bleu + Rouge)
From Stack Overflow: asked by Chelsea_cole, answered by eiTan LaVi (CC BY-SA 3.0)
Hamming Distance vs. Levenshtein Distance
That question really depends on the types of sequences you are matching, and what result you want.
If it's not a problem that "1234567890" and "0123456789" are considered totally different, indeed Hamming distance is fine.
From Stack Overflow: asked by don, answered by Johan Kotlinski (CC BY-SA 2.5)
What do the BILOU tags mean in Named Entity Recognition?
Based on an issue and a patch in Clear TK, it seems like BILOU stands for "Beginning, Inside and Last tokens of multi-token chunks, Unit-length chunks and Outside" (emphasis added). For instance, the chunking denoted by brackets
(foo foo foo) (bar) no no no (bar bar)can be encoded with BILOU as
B-foo, I-foo, L-foo, U-bar, O, O, O, B-bar, L-barFrom Stack Overflow: asked by GrantD71, answered by mbatchkarov (CC BY-SA 3.0)
How to compute the similarity between two text documents?
The common way of doing this is to transform the documents into TF-IDF vectors and then compute the cosine similarity between them. Any textbook on information retrieval (IR) covers this. See esp. Introduction to Information Retrieval, which is free and available online.
Computing Pairwise Similarities
TF-IDF (and similar text transformations) are implemented in the Python packages Gensim and scikit-learn. In the latter package, computing cosine similarities is as easy as
from sklearn.feature_extraction.text import TfidfVectorizer documents = [open(f).read() for f in text_files] tfidf = TfidfVectorizer().fit_transform(documents) # no need to normalize, since Vectorizer will return normalized tf-idf pairwise_similarity = tfidf * tfidf.Tor, if the documents are plain strings,
>>> corpus = ["I'd like an apple", ... "An apple a day keeps the doctor away", ... "Never compare an apple to an orange", ... "I prefer scikit-learn to Orange", ... "The scikit-learn docs are Orange and Blue"] >>> vect = TfidfVectorizer(min_df=1, stop_words="english") >>> tfidf = vect.fit_transform(corpus) >>> pairwise_similarity = tfidf * tfidf.Tthough Gensim may have more options for this kind of task.
See also this question.
[Disclaimer: I was involved in the scikit-learn TF-IDF implementation.]
Interpreting the Results
From above,
pairwise_similarityis a Scipy sparse matrix that is square in shape, with the number of rows and columns equal to the number of documents in the corpus.>>> pairwise_similarity <5x5 sparse matrix of type '<class 'numpy.float64'>' with 17 stored elements in Compressed Sparse Row format>You can convert the sparse array to a NumPy array via
.toarray()or.A:>>> pairwise_similarity.toarray() array([[1. , 0.17668795, 0.27056873, 0. , 0. ], [0.17668795, 1. , 0.15439436, 0. , 0. ], [0.27056873, 0.15439436, 1. , 0.19635649, 0.16815247], [0. , 0. , 0.19635649, 1. , 0.54499756], [0. , 0. , 0.16815247, 0.54499756, 1. ]])Read the rest at the sourceFrom Stack Overflow: asked by Reily Bourne, answered by Fred Foo (CC BY-SA 4.0)
How to determine the language of a piece of text?
1. TextBlob. (Deprecated - Use official Google Translate API instead)
Requires NLTK package, uses Google.
from textblob import TextBlob b = TextBlob("bonjour") b.detect_language()pip install textblobNote: This solution requires internet access and Textblob is using Google Translate's language detector by calling the API.
2. Polyglot.
Requires numpy and some arcane libraries, unlikely to get it work for Windows. (For Windows, get an appropriate versions of PyICU, Morfessor and PyCLD2 from here, then just
pip install downloaded_wheel.whl.) Able to detect texts with mixed languages.from polyglot.detect import Detector mixed_text = u""" China (simplified Chinese: 中国; traditional Chinese: 中國), officially the People's Republic of China (PRC), is a sovereign state located in East Asia. """ for language in Detector(mixed_text).languages: print(language) # name: English code: en confidence: 87.0 read bytes: 1154 # name: Chinese code: zh_Hant confidence: 5.0 read bytes: 1755 # name: un code: un confidence: 0.0 read bytes: 0pip install polyglotTo install the dependencies, run:
sudo apt-get install python-numpy libicu-devNote: Polyglot is using
pycld2, see https://github.com/aboSamoor/polyglot/blob/master/polyglot/detect/base.py#L72 for details.3. chardet
Chardet has also a feature of detecting languages if there are character bytes in range (127-255]:
>>> chardet.detect("Я люблю вкусные пампушки".encode('cp1251')) {'encoding': 'windows-1251', 'confidence': 0.9637267119204621, 'language': 'Russian'}pip install chardet4. langdetect
Requires large portions of text. It uses non-deterministic approach under the hood. That means you get different results for the same text sample. Docs say you have to use following code to make it determined:
from langdetect import detect, DetectorFactory DetectorFactory.seed = 0 detect('今一はお前さん')pip install langdetect5. guess_language
Can detect very short samples by using this spell checker with dictionaries.
pip install guess_language-spirit6. langid
langid.py provides both a module
import langid langid.classify("This is a test") # ('en', -54.41310358047485)and a command-line tool:
$ langid < README.mdpip install langid7. FastText
FastText is a text classifier, can be used to recognize 176 languages with a proper models for language classification. Download this model, then:
Read the rest at the sourceFrom Stack Overflow: asked by Rita, answered by Rabash (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Data Science Interviewsby Alexey Grigorev and contributorsCC BY 4.012 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA20 questions
- Data Science Stack Exchangeby its contributors, named on each answerCC BY-SA20 questions