id
int64
0
25.6k
text
stringlengths
0
4.59k
17,600
the last few lines select the best model first we compare the predictionspredwith the actual labelsvirginica the little trick of computing the mean of the comparisons gives us the fraction of correct resultsthe accuracy at the end of the for loopall possible thresholds for all possible features have been testedand the ...
17,601
evaluation holding out data and cross-validation the model discussed in the preceding section is simple modelit achieves percent accuracy on its training data howeverthis evaluation may be overly optimistic we used the data to define what the threshold would beand then we used the same data to evaluate the model of cou...
17,602
error for ei in range(len(features))select all but the one at position 'ei'training np ones(len(features)booltraining[eifalse testing ~training model learn_model(features[training]virginica[training]predictions apply_model(features[testing]virginica[testing]modelerror +np sum(predictions !virginica[testing]at the end o...
17,603
the preceding figure illustrates this process for five blocksthe dataset is split into five pieces then for each foldyou hold out one of the blocks for testing and train on the other four you can use any number of folds you wish five or ten fold is typicalit corresponds to training with or percent of your data and shou...
17,604
we can play around with these parts to get different results for examplewe can attempt to build threshold that achieves minimal training errorbut we will only test three values for each featurethe mean value of the featuresthe mean plus one standard deviationand the mean minus one standard deviation this could make sen...
17,605
learning about the seeds dataset we will now look at another agricultural datasetit is still smallbut now too big to comfortably plot exhaustively as we did with iris this is dataset of the measurements of wheat seeds seven features are presentas followsarea (aperimeter (pcompactness length of kernel width of kernel as...
17,606
features and feature engineering one interesting aspect of these features is that the compactness feature is not actually new measurementbut function of the previous two featuresarea and perimeter it is often very useful to derive new combined features this is general area normally termed feature engineeringit is somet...
17,607
nearest neighbor classification with this dataseteven if we just try to separate two classes using the previous methodwe do not get very good results let me introduce thereforea new classifierthe nearest neighbor classifier if we consider that each example is represented by its features (in mathematical termsas point i...
17,608
in the preceding screenshotthe canadian examples are shown as diamondskama seeds as circlesand rosa seeds as triangles their respective areas are shown as whiteblackand grey you might be wondering why the regions are so horizontalalmost weirdly so the problem is that the axis (arearanges from to while the axis (compact...
17,609
independent of what the original values wereafter -scoringa value of zero is the mean and positive values are above the mean and negative values are below it now every feature is in the same unit (technicallyevery feature is now dimensionlessit has no unitsand we can mix dimensions more confidently in factif we now run...
17,610
binary and multiclass classification the first classifier we sawthe threshold classifierwas simple binary classifier (the result is either one class or the other as point is either above the threshold or it is notthe second classifier we usedthe nearest neighbor classifierwas naturally multiclass classifier (the output...
17,611
there are many other possible ways of turning binary method into multiclass one there is no single method that is clearly better in all cases howeverwhich one you use normally does not make much of difference to the final result most classifiers are binary systems while many real-life problems are naturally multiclass ...
17,612
related posts in the previous we have learned how to find classes or categories of individual data points with handful of training data items that were paired with their respective classeswe learned model that we can now use to classify future data items we called this supervised learningas the learning was guided by t...
17,613
we will achieve this goal in this using clustering this is method of arranging items so that similar items are in one cluster and dissimilar items are in distinct ones the tricky thing that we have to tackle first is how to turn text into something on which we can calculate similarity with such measurement for similari...
17,614
how to do it more robust than edit distance is the so-called bag-of-word approach it uses simple word counts as its basis for each word in the postits occurrence is counted and noted in vector not surprisinglythis step is also called vectorization the vector is typically huge as it contains as many elements as the word...
17,615
converting raw text into bag-of-words we do not have to write custom code for counting words and representing those counts as vector scikit' countvectorizer does the job very efficiently it also has very convenient interface scikit' functions and classes are imported via the sklearn package as followsfrom sklearn featu...
17,616
this means that the first sentence contains all the words except for "problems"while the second contains all except "how""my"and "toin factthese are exactly the same columns as seen in the previous table from xwe can extract feature vector that we can use to compare the two documents with each other first we will start...
17,617
unsurprisinglywe have five posts with total of different words the following words that have been tokenized will be countedprint(vectorizer get_feature_names()[ 'about' 'actually' 'capabilities' 'contains' 'data' 'databases' 'images' 'imaging' 'interesting' 'is' 'it' 'learning' 'machine' 'most' 'much' 'not' 'permanentl...
17,618
post posts[iif post==new_postcontinue post_vec x_train getrow(id dist(post_vecnew_post_vecprint "==post % with dist= % "%(idpostif <best_distbest_dist best_i print("best post is % with dist= "%(best_ibest_dist)==post with dist= this is toy post about machine learning actuallyit contains not much interesting stuff ==pos...
17,619
normalizing the word count vectors we will have to extend dist_raw to calculate the vector distancenot on the raw vectors but on the normalized ones insteaddef dist_norm( ) _normalized /sp linalg norm( toarray() _normalized /sp linalg norm( toarray()delta _normalized _normalized return sp linalg norm(delta toarray()thi...
17,620
if you have clear picture of what kind of stop words you would want to removeyou can also pass list of them setting stop_words to "englishwill use set of english stop words to find out which ones they areyou can use get_stop_ words()sorted(vectorizer get_stop_words())[ : [' ''about''above''across''after''afterwards''ag...
17,621
installing and using nltk how to install nltk on your operating system is described in detail at packages nltk and pyyaml to check whether your installation was successfulopen python interpreter and type the followingimport nltk you will find very nice tutorial for nltk in the book python text processing with nltk cook...
17,622
extending the vectorizer with nltk' stemmer we need to stem the posts before we feed them into countvectorizer the class provides several hooks with which we could customize the preprocessing and tokenization stages the preprocessor and tokenizer can be set in the constructor as parameters we do not want to place the s...
17,623
==post with dist= imaging databases store data ==post with dist= imaging databases store data imaging databases store data imaging databases store data best post is with dist= stop words on steroids now that we have reasonable way to extract compact vector from noisy textual postlet us step back for while to think abou...
17,624
print(tfidf(" "abbd) print(tfidf(" "abcd) print(tfidf(" "abcd) print(tfidf(" "abcd) we see that carries no meaning for any document since it is contained everywhere is more important for the document abb than for abc as it occurs there twice in realitythere are more corner cases to handle than the above example does th...
17,625
throwing away words that occur so seldom that there is only small chance that they occur in future posts counting the remaining words calculating tf-idf values from the countsconsidering the whole text corpus again we can congratulate ourselves with this processwe are able to convert bunch of noisy text into concise re...
17,626
flat clustering divides the posts into set of clusters without relating the clusters to each other the goal is simply to come up with partitioning such that all posts in one cluster are most similar to each other while being dissimilar from the posts in all other clusters many flat clustering algorithms require the num...
17,627
let us play this through with toy example of posts containing only two words each point in the following chart represents one documentafter running one iteration of kmeansthat istaking any two vectors as starting pointsassigning labels to the restand updating the cluster centers to be the new center point of all points...
17,628
because the cluster centers are movedwe have to reassign the cluster labels and recalculate the cluster centers after iteration we get the following clusteringthe arrows show the movements of the cluster centers after five iterations in this examplethe cluster centers don' move noticeably any more (scikit' tolerance th...
17,629
one standard dataset in machine learning is the newsgroup datasetwhich contains , posts from different newsgroups among the groupstopics are technical ones such as comp sys mac hardware or sci crypt as well as more politicsand religion-related ones such as talk politics guns or soc religion christian we will restrict o...
17,630
' :\\data\\ \\raw\\comp os ms-windows misc\\ - ']dtype='| 'print(len(data filenames) data target_names ['alt atheism''comp graphics''comp os ms-windows misc''comp sys ibm pc hardware''comp sys mac hardware''comp windows ''misc forsale''rec autos''rec motorcycles''rec sport baseball''rec sport hockey''sci crypt''sci ele...
17,631
num_samplesnum_features vectorized shape print("#samples% #features% (num_samplesnum_features)#samples #features we now have pool of , posts and extracted for each of them feature vector of , dimensions that is what kmeans takes as input we will fix the cluster size to for this and hope you are curious enough to try ou...
17,632
as we have learned previouslywe will first have to vectorize this post before we predict its label as followsnew_post_vec vectorizer transform([new_post]new_post_label km predict(new_post_vec)[ now that we have the clusteringwe do not need to compare new_post_vec to all post vectors insteadwe can focus only on the post...
17,633
the following table shows the posts together with their similarity valuesposition similarity excerpt from post boot problem with ide controller hii've got multi / card (ide controller serial/parallel interfaceand two floppy drives ( / / and quantum prodrive at connected to it was able to format the hard diskbut could n...
17,634
position similarity excerpt from post conner cp info please how to change the cluster size wondering if somebody could tell me if we can change the cluster size of my ide drive normally can do it with norton' calibrat on mfm/rll drives but dunno if can on ide too it is interesting how the posts reflect the similarity m...
17,635
this is only after tokenizationlower casingand stop word removal if we also subtract those words that will be later filtered out via min_df and max_dfwhich will be done later in fit_transformit gets even worselist(set(analyzer( [ ][ ])intersectionvectorizer get_feature_names())[ 'cs' 'faq' 'thank'list(set(analyzer( [ ]...
17,636
but before you go thereyou will have to define what you actually mean by "betterscikit has complete package dedicated only to this definition the package is called sklearn metrics and also contains full range of different metrics to measure clustering quality maybe that should be the first place to go nowright into the...
17,637
in the previous we clustered texts into groups this is very useful toolbut it is not always appropriate clustering results in each text belonging to exactly one cluster this book is about machine learning and python should it be grouped with other python-related works or with machine-related worksin the paper book agea...
17,638
for those who are interested and adventurous enougha wikipedia search will provide all the equations behind these algorithms at the following linkhoweverwe can understand that this is at high level and there is sort of fable which underlies these models in this fablethere are topics that are fixed this lacks clarity wh...
17,639
corpus is just the preloaded list of wordsmodel models ldamodel ldamodelcorpusnum_topics= id word=corpus id wordthis one-step process will build topic model we can explore the topics in many ways we can see the list of topics document refers to by using the model[docsyntaxtopics [model[cfor in corpusprint topics[ [( )(...
17,640
sparsity means that while you may have large matrices and vectorsin principlemost of the values are zero (or so small that we can round them to zero as good approximationthereforeonly few things are relevant at any given time often problems that seem too big to solve are actually feasible because the data is sparse for...
17,641
now we can see that many documents touch upon to different topics what are these topicstechnicallythey are multinomial distributions over wordswhich mean that they give each word in the vocabulary probability words with high probability are more associated with that topic than words with lower probability our brains ar...
17,642
although daunting at first glancewe can clearly see that the topics are not just random wordsbut are connected we can also see that these topics refer to older news itemsfrom when the soviet union still existed and gorbachev was its secretary general we can also represent the topics as word cloudsmaking more likely wor...
17,643
howevertopics are often just an intermediate tool to another end now that we have an estimate for each document about how much of that document comes from each topicwe can compare the documents in topic space this simply means that instead of comparing word per wordwe say that two documents are similar if they talk abo...
17,644
for tj, in tdense[ti,tjv nowdense is matrix of topics we can use the pdist function in scipy to compute all pairwise distances that iswith single function callwe compute all the values of sum((dense[tidense[tj])** )from scipy spatial import distance pairwise distance squareform(distance pdist(dense)now we employ one la...
17,645
subjectrehigh prolactin in article jer @psuvm psu edu (john rodwaywrites>any comments on the use of the drug parlodel for high prolactin in the blood>it can suppress secretion of prolactin is useful in cases of galactorrhea some adenomas of the pituitary secret too much gordon banks jxp "skepticism is the chastity of t...
17,646
finallywe build the lda model as beforemodel gensim models ldamodel ldamodelcorpus=mmid word=id wordnum_topics= update_every= chunksize= passes= this will again take couple of hours (you will see the progress on your consolewhich can give you an indication of how long you still have to waitonce it is doneyou can save i...
17,647
we can also ask what the most talked about topic in wikipedia is we first collect some statistics on topic usagecounts np zeros( for doc_top in topicsfor ti, in doc_topcounts[ti+ words model show_topic(counts argmax() using the same tool as before to build up visualizationwe can see that the most talked about topic is ...
17,648
alternativelywe can look at the least talked about topicwords model show_topic(counts argmin() the least talked about are the former french colonies in central africa just percent of documents touch upon itand it represents percent of the words probably if we had performed this exercise using the french wikipediawe wou...
17,649
if you are going to explore the topics yourself or build visualization toolyou should probably try few values and see which gives you the most useful or most appealing results howeverthere are few methods that will automatically determine the number of topics for you depending on the dataset one popular model is called...
17,650
topic modeling was first developed and is easier to understand in the case of textbut in computer vision pattern recognitionwe will see how some of these techniques may be applied to images as well topic models are very important in most of modern computer vision research in factunlike the previous this was very close ...
17,651
poor answers now that we are able to extract useful features from textwe can take on the challenge of building classifier using real data let' go back to our imaginary website in clustering finding related postswhere users can submit questions and get them answered continuous challenge for owners of these & sites is to...
17,652
sketching our roadmap we will build system using real data that is very noisy this is not for the faintheartedas we will not arrive at the golden solution for classifier that achieves percent accuracy this is because even humans often disagree whether an answer was good or not (just look at some of the comments on the ...
17,653
fetching the data luckily for usthe team behind stackoverflow provides most of the data behind the stackexchange universe to which stackoverflow belongs under cc wiki license while writing thisthe latest data dump can be found at net/torrents/ -aug- most likelythis page will contain pointer to an updated dump when you ...
17,654
name type description id integer this is unique identifier posttype integer this describes the category of the post the following values are of interest to usquestion answer other values will be ignored parentid integer this is unique identifier of the question to which this answer belongs (missing for questionscreatio...
17,655
preselection and processing of attributes we should also only keep those attributes that we think could help the classifier in determining the good from the not-so-good answers certainlywe need the identification-related attributes to assign the correct answers to the questions read the following attributesthe posttype...
17,656
we end up with the following formatid parentid isaccepted timetoanswer score text for concrete parsing detailsplease refer to so_xml_to_tsv py and choose_ instance py it will suffice to say that in order to speed up the processwe will split the data into two files in meta jsonwe store dictionarymapping post' id to its ...
17,657
creating our first classifier let us start with the simple and beautiful nearest neighbor method from the previous although it is not as advanced as other methodsit is very powerful as it is not model-basedit can learn nearly any data howeverthis beauty comes with clear disadvantagewhich we will find out very soon star...
17,658
engineering the features sowhat kind of features can we provide to our classifierwhat do we think will have the most discriminative powerthe timetoanswer attribute is already present in our meta dictionarybut it probably won' provide much value on its own then there is only textbut in its raw formwe cannot pass it to t...
17,659
with the majority of posts having no link at allwe now know that this feature alone will not make good classifier let us nevertheless try it out to get first estimation of where we are training the classifier we have to pass the feature array together with the previously defined labels to the knn learner to obtain clas...
17,660
but as we learned in the previous we will not do it just oncebut apply cross-validation here using the ready-made kfold class from sklearn cross_ validation finallywe will average the scores on the test set of each fold and see how much it varies using standard deviation refer to the following codefrom sklearn cross_va...
17,661
which we don' want to count link_count_in_code +len(link_match findall(match_str)links link_match findall(slink_count len(linkslink_count -link_count_in_code html_free_s re sub(+""tag_match sub(''code_free_s)replace("\ """link_free_s html_free_s remove links from text before counting words for anchor in anchorsif ancho...
17,662
but stillthis would mean that we could classify roughly four out of the ten wrong answers at least we are heading in the right direction more features lead to higher accuracywhich leads us to adding more features thereforelet us extend the feature space with even more featuresavgsentlenthis feature measures the average...
17,663
with these four additional featureswe now have seven features representing individual posts let' see how we have progressedmean(scores)= stddev(scores)= now that' interesting we added four more features and got worse classification accuracy how can that be possibleto understand thiswe have to remind ourselves of how kn...
17,664
modify the feature spaceit may be that we do not have the right set of features we couldfor examplechange the scale of our current features or design even more new features or ratherwe could remove some of our current features in case some features are aliasing others change the modelit may be that knn is generally not...
17,665
the only possibilities we have in this case is to either get more featuresmake the model more complexor change the model fixing high variance ifon the contrarywe suffer from high variance that means our model is too complex for the data in this casewe can only try to get more data or decrease the complexity this would ...
17,666
looking at the previous graphwe immediately see that adding more training data will not helpas the dashed line corresponding to the test error seems to stay above the only option we have is to decrease the complexity either by increasing or by reducing the feature space reducing the feature space does not help here we ...
17,667
but this is not enoughand it comes at the price of lower classification runtime performance takefor instancethe value of where we have very low test error to classify new postwe need to find the nearest other posts to decide whether the new post is good one or notclearlywe seem to be facing an issue with using the near...
17,668
bit of math with small example to get an initial understanding of the way logistic regression workslet us first take look at the following examplewhere we have an artificial feature value at the axis plotted with the corresponding class rangeeither or as we can seethe data is so noisy that classes overlap in the featur...
17,669
this means that we can now fit linear combinations of our features (okwe have only one feature and constantbut that will change soonto the values let' consider the linear equation in getting started with python machine learning shown as followsthis can be replaced with the following equation (by replacing with )we can ...
17,670
clf fit(xyprint(np exp(clf intercept_)np exp(clf coef_ ravel()) def lr_model(clfx)return ( np exp(-(clf intercept_ clf coef_* ))print(" ( =- )= \tp( = )= "%(lr_model(clf- )lr_ model(clf )) ( =- )= ( = )= you might have noticed that scikit-learn exposes the first coefficient through the special field intercept_ if we pl...
17,671
method mean(scoresstddev(scoreslogreg = nn we have seen the accuracy for the different values of the regularization parameter with itwe can control the model complexitysimilar to the parameter for the nearest neighbor method smaller values for result in higher penaltythat isthey make the model more complex quick look a...
17,672
looking behind accuracy precision and recall let us step back and think again what we are trying to achieve here actuallywe do not need classifier that perfectly predicts good and bad answersas we measured it until now using accuracy if we can tune the classifier to be particularly good in predicting one classwe could ...
17,673
if instead our goal would have been to detect as much good or bad answers as possiblewe would be more interested in recallthe next screenshot shows all the good answers and the answers that have been classified as being good onesin terms of the previous diagramprecision is the fraction of the intersection of the right ...
17,674
predicting one class with acceptable performance does not always mean that the classifier will predict the other classes acceptably this can be seen in the following two graphs where we plot the precision/recall curves for classifying bad (left graph of the next screenshotand good (right graph of the next screenshotans...
17,675
setting the threshold at we see that we can still achieve precision of above percentdetecting good answers when we accept low recall of percent this means that we will detect only one in three bad answersbut those answers that we manage to detect we would be reasonably sure of to apply this threshold in the prediction ...
17,676
slimming the classifier it is always worth looking at the actual contributions of the individual features for logistic regressionwe can directly take the learned coefficients (clf coef_to get an impression of the feature' impact the higher the coefficient of feature isthe more the feature plays role in determining whet...
17,677
ship itlet' assume we want to integrate this classifier into our site what we definitely do not want is to train the classifier each time we start the classification service insteadwe can simply serialize the classifier after training and then deserialize it on that siteimport pickle pickle dump(clfopen("logreg dat"" "...
17,678
analysis for companiesit is vital to closely monitor the public reception of key events such as product launches or press releases with real-time access and easy accessibility of user-generated content on twitterit is now possible to do sentiment classification of tweets sometimes also called opinion miningit is an act...
17,679
fetching the twitter data naturallywe need tweets and their corresponding labels that tell us whether tweet contains positivenegativeor neutral sentiment in this we will use the corpus from niek sanderswho has done an awesome job of manually labeling more than tweets and granted us permission to use it in this to compl...
17,680
getting to know the bayes theorem at its corenaive bayes classification is nothing more than keeping track of which feature gives evidence to which class to ease our understandinglet us assume the following meanings for the variables that we will use to explain naive bayesvariable possible values meaning "pos""negclass...
17,681
the prior and evidence values are easily determinedis the prior probability of class without knowing about the data this quantity can be obtained by simply calculating the fraction of all training data instances belonging to that particular class is the evidenceor the probability of features and this can be retrieved b...
17,682
using naive bayes to classify given new tweetthe only part left is to simply calculate the probabilitieswe also need to choose the class having the higher probability as for both classes the denominatoris the sameso we can simply ignore it without changing the winner class notehoweverthat we don' calculate any real pro...
17,683
in this casewe have six total tweetsout of which four are positive and two negativewhich results in the following priorsthis meanswithout knowing anything about the tweet itselfwe would be wise in assuming the tweet to be positive and the piece that is still missing is the calculation of probabilities for the two featu...
17,684
this denotation "leads to the following valuesnow we have all the data to classify new tweets the only work left is to parse the tweet and give features to it tweet class probabilities classification awesome positive crazy negative awesome crazy positive awesome text undefinedbecause we have never seen these words in t...
17,685
accounting for unseen words and other oddities when we calculated the preceding probabilitieswe actually cheated ourselves we were not calculating the real probabilitiesbut only rough approximations by means of the fractions we assumed that the training corpus would tell us the whole truth about the real probabilities ...
17,686
similarlywe do this for the prior probabilitiesaccounting for arithmetic underflows there is yet another roadblock in realitywe work with probabilities much smaller than the ones we have dealt with in the toy example in realitywe also have more than two featureswhich we multiply with each other this will quickly lead t...
17,687
fortunatelythere is better way to take care of thisand it has to do with nice relationship that we maybe still know from schoolif we apply it to our casewe get the followingas the probabilities are in the interval between and the log of the probabilities lies in the interval and don' get irritated with that higher numb...
17,688
quick look at the previous graph shows that the curve never goes down when we go from left to right in shortapplying the logarithm does not change the highest value solet us stick this into the formula we used earlierwe will use this to retrieve the formula for two features that will give us the best class for real-wor...
17,689
solving an easy problem first as we have seen when we looked at our tweet datathe tweets are not just positive or negative the majority of tweets actually do not contain any sentimentbut are neutral or irrelevantcontainingfor instanceraw information (new bookbuilding machine learning avoid complicating the task too muc...
17,690
to keep our experimentation agilelet us wrap everything together in train_ model(functionwhich takes function as parameter that creates the classifierfrom sklearn metrics import precision_recall_curveauc from sklearn cross_validation import shufflesplit def train_model(clf_factoryxy)setting random_state to get determin...
17,691
with our first try of using naive bayes on vectorized tf-idf trigram featureswe get an accuracy of percent and / auc of percent looking at the / chart shown in the following screenshotit shows much more encouraging behavior than the plots we saw in the previous for the first timethe results are quite encouraging they g...
17,692
np zeros( shape[ ] [pos astype(intreturn note that we are talking about two different positives now the sentiment of tweet can be positivewhich is to be distinguished from the class of the training data iffor examplewe want to find out how good we can separate the tweets having sentiment from neutral oneswe could do th...
17,693
sohow would the naive bayes classifier perform on classifying positive tweets versus the rest and negative tweets versus the restone wordbad =pos vs rest = =neg vs rest = pretty unusable if you ask me looking at the / curves shown in the following screenshotswe also find no usable precision/recall tradeoff as we were a...
17,694
degdeg experiment with whether or not to use the logarithm of the word counts (sublinear_tfdegdeg experiment with whether or not to track word counts or simply track whether words occur or not by setting binary to true or false multinomialnb degdeg decide which of the following smoothing methods to use by setting alpha...
17,695
the only missing thing is to define how gridsearchcv should determine the best estimator this can be done by providing the desired score function to (surprise!the score_func parameter we could either write one ourselves or pick one from the sklearn metrics package we should certainly not take metric accuracy because of...
17,696
we have to be patient when executing the following codeclf grid_search_model(create_ngram_modelxyprint clf this is because we have just requested parameter sweep over the parameter combinations--each being trained on foldswaiting some hours pipeline(clf=multinomialnbalpha= class_weight=nonefit_prior=true)clf__alpha= cl...
17,697
the devastating results for positive tweets against the rest and negative tweets against the rest will improve if we configure the vectorizer and classifier with those parameters that we have just found out=pos vs rest = =neg vs rest = indeedthe / curves look much better (note that the graphs are from the medium of the...
17,698
firstwe define range of frequent emoticons and their replacements in dictionary although we could find more distinct replacementswe go with obvious positive or negative words to help the classifieremo_repl positive emoticons "&lt; "good "": "good ": in lower case ":dd"good ":dd in lower case " )"good "":-)"good "":)"go...
17,699
"\bwouldn' \ ""would not" "\bcan' \ ""can not" "\bcannot\ ""can not"def create_ngram_model(params=none)def preprocessor(tweet)global emoticons_replaced tweet tweet lower(#return tweet lower(for in emo_repl_ordertweet tweet replace(kemo_repl[ ]for rrepl in re_repl iteritems()tweet re sub(rrepltweetreturn tweet tfidf_ngr...