id
int64
0
25.6k
text
stringlengths
0
4.59k
16,000
let' try to extract the first three principal components now from our breast cancer feature set of features using svd we first center our feature matrix and then use svd and subsetting to extract the first three pcs using the following code in [ ]center the feature set bc_xc bc_x bc_x mean(axis= decompose using svd usv...
16,001
from the preceding outputas expectedwe can see the maximum variance is explained by the first principal component to obtain the reduced feature setwe can use the following snippet in [ ]bc_pca pca transform(bc_xnp round(bc_pca out[ ]array([ - ] - ] - ] - ] - ]- - ]]if you compare the values of this reduced feature set ...
16,002
temporal and images multiple feature scaling techniques are also coveredwhich are useful to tone down the scale and magnitude of features before modeling finallywe cover feature selection techniques in detail with emphasis on the three different strategies of feature selection namely filterwrapperand embedded methods s...
16,003
buildingtuningand deploying models very popular saying in the machine learning community is " of machine learning is data processingand going by the structure of this bookthe quote seems quite apt in the preceding you saw how you can extractprocessand transform data to convert it to form suitable for learning using mac...
16,004
uilding models before we get on with the process of building modelswe should try to understand what model represents in the simplest of termsa model can be described as relationship between output or response variables and its corresponding input or independent variables in dataset sometimes this relationship can just ...
16,005
building or learning process usually these hyperparameters are tuned to get the optimal values as part of the model-tuning phase ( part of the learning phase itself another important point to remember is that the output model is generally dependent on the learning algorithm we choose for our data model types models ca...
16,006
classification models can be further broken down on the type of output variables and the number of output variables produced by them this nomenclature is extremely important to understand the type of classification problem you are dealing with by looking at the dataset attributes and the objective to be solved binary c...
16,007
based on the number of variablesthe probability distribution of output variables and form of relationship (linear versus nonlinear)we have different types of regression models the following are some of the major categories of regression models simple linear regressionit is the simplest of all the regression modelsbut i...
16,008
clustering models can be of different types on the basis of clustering methodologies and principles we will briefly introduce the different types of clustering algorithmswhich are as follows partition based clusteringa partition based clustering method is the most natural way to imagine the process of clustering partit...
16,009
three stages of machine learning machine learning can often be complex field we have different types of problems and tasks and different algorithms to solve them we also have complex mathstatsand logic that form the very backbone of this diverse field if you rememberyou learned in the first that machine learning is co...
16,010
on the representation and the evaluation aspects optimization methods can be methods like gradient descent and even meta-heuristical methods like generic algorithms the three stages of logistic regression the best way to understand the nuances of complex process is to explain it using an example in this sectionwe trac...
16,011
optimization the cost function we described earlier is function of th and hence we need to maximize the previous function and find the set of th that gives us the maximum value (normally we will minimize the cost functionbut here we have taken log and hence we will maximize the log functionthe value th that we obtain ...
16,012
classification in all classification (or supervised learningproblemsthe first step after preparing the whole dataset is to segregate the data into testing and training set and optionally validation set the idea is to make the model learn by training it on the train datasetevaluate and tune it on the validation dataset...
16,013
we can determine how the raw pixel data looks the flattened vector representation and the number (class label)which is represented by the image using the following code actual image pixel matrix in [ ]digits images[ out[ ]array([ ] ] ] ] ] ] ] ]]flattened vector in [ ]digits data[ out[ ]array( ]image class label in [ ]...
16,014
in [ ]from sklearn import linear_model logistic linear_model logisticregression(logistic fit(x_trainy_trainlogisticregression( = class_weight=nonedual=falsefit_intercept=trueintercept_scaling= max_iter= multi_class='ovr'n_jobs= penalty=' 'random_state=nonesolver='liblinear'tol= verbose= warm_start=falseyou can see vari...
16,015
partition based clustering we will choose the simplest yet most popular partition based clustering model for our examplewhich is -means algorithm this algorithm is centroid based clustering algorithmwhich starts with some assumption about the total clusters in the data and with random centers assigned to each of the c...
16,016
if labels[ = ax scatter(bc_pca[ , ]bc_pca[ , ], =' 'marker='if labels[ = ax scatter(bc_pca[ , ]bc_pca[ , ], =' 'marker=' ax legend([ ][' '' '] ax legend([ ][' '' ']figure - visualizing clusters in the breast cancer dataset from figure - you can clearly see that the clustering has worked quite well and it shows distinct...
16,017
hierarchical clustering we can use the same data to perform hierarchical clustering and see if the results change much as compared to -means clustering and the actual labels in scikit-learn we have multitude of interfaces like the agglomerativeclustering class to perform hierarchical clustering based on what we discus...
16,018
figure - visualizing the hierarchical clustering dendrogram in the dendrogram depicted in figure - we can see how each data point starts as an individual cluster and slowly starts getting merged with other data points to form clusters on high level from the colors and the dendrogramyou can see that the model has correc...
16,019
we definitely see two distinct clusters but there is more overlap as compared to the -means method between the two clusters and we have more mislabeled instances howeverdo take note of the label numbershere we have and as the label values this is just to reinforce the fact that the label values are just to distinguish ...
16,020
from the preceding outputit is clear that we have observations in our train dataset and observations in our test dataset we will be leveraging nifty module we have created for model evaluation it is named model_evaluation_utils and you can find it along with the code files and notebooks for this we recommend you to che...
16,021
are interested in detecting or predicting when the patient does not have breast cancer (benignthen label is our positive class howeversuppose our class of interest was to detect cancer (malignantthen we could have chosen label as our positive class figure - shows typical confusion matrix for binary classification probl...
16,022
thus based on this informationcan you compute the previously mentioned metrics for our confusion matrix based on the model predictions on the breast cancer test datapositive_class tp fp tn fn performance metrics the confusion matrix by itself is not performance measure for classification models but it can be used to c...
16,023
framework precision manually computed precision recallrecallalso known as sensitivityis measure of model to identify the percentage of relevant data points it is defined as the number of instances of the positive class that were correctly predicted this is also known as hit ratecoverageor sensitivity the formula for re...
16,024
receiver operating characteristic curve roc which stands for receiver operating characteristic is concept from early radar days this concept can be extended to evaluation of binary classifiers as well as multi-class classifiers (note that to adapt the roc curve for multi-class classifiers we have to use one-vs-all sch...
16,025
figure - sample roc curve (sourcehtml#roc-metricsfigure - depicts the sample roc curve in generalthe roc curve is an important tool for visually interpreting classification models but it doesn' directly provide us with numerical value that we can use to compare models the metric which does that task is the area under c...
16,026
figure - roc curve for our logistic regression model considering our model has an accuracy and score of around %figure - makes sense where we see near perfect roc curvecheck out to see multi-class classifier roc curve in actionevaluating clustering models we discussed some of the popular ways to evaluate classificatio...
16,027
if you remember our discussion earlier on cluster labelsthey are just indicators used to distinguish data points from each other based on which cluster or group they fall into hence we cannot compare cluster with label directly with true class label it is possible that all data points with true class label of were actu...
16,028
silhouette coefficient silhouette coefficient is metric that tries to combine the two requirements of good clustering model the silhouette coefficient is defined for each sample and is combination of its similarity to the data points in its own cluster and its dissimilarity to the data points not in its cluster the ma...
16,029
herek wk aa ) = xic bk anq ) with tr being the trace of matrix operatorn being the number of data points in our datacq being the set of points in cluster qcq being the center of cluster qc being the center of eand nq being the number of points in cluster thankfully we can calculate this index without having to calculat...
16,030
in the scikit-learn packagethis can be calculated by using the _score function by supplying it the true values and the predicted values (of the output\response variablemean squared error mean squared error calculates the average of the squares of the errors or deviation between the actual value and the predicted value...
16,031
introduction to hyperparameters what are hyperparametersthe simplest definition is that hyperparameters are meta parameters that are associated with any machine learning algorithm and are usually set before the model training and building process we do this because model hyperparameters do not have any dependency on b...
16,032
figure - sample decision tree model the decision tree is easy to interpret by following the path with the values of an unknown data point the leaf node where you end up is the predicted class for the data point the model parameters in this case are the attributes on which we are splitting (here sexageand sibspand the v...
16,033
biasthis is the error that arises due to the model (learning algorithmmaking wrong assumptions on the parameters in the underlying data the bias error is the difference between the expected or predicted value of the model estimator and the true or actual value which we are trying to predict if you remembermodel buildin...
16,034
figure - the bias-variance tradeoff in figure - the inner red circle represents the perfect model that we can have considering all the combinations of the data that we can get each blue dot (marks model that we have learned on the basis of combinations of the dataset and features that we get models with low biaslow var...
16,035
models with high biashigh variance are the worst sort of models possibleas they will not learn necessary data attribute relationships that are essential to correlation with output responses also they will be extremely sensitive to data and outliers and noise leading to highly fluctuating predictions which result in hig...
16,036
figure - test and train errors as function of model complexity (sourcethe elements of statistical learningtibshirani et al springerfigure - should give you more clarity on the tradeoff that needs to be done to prevent an increase in model errors we will need to make some assumptions about the underlying structure in th...
16,037
in theorywe can extend the same principles for tuning our algorithm we can evaluate the performance of particular values of the model hyperparameters on the test set retrain the model with different partition of training and test set with different values of hyperparameters if the new parameters perform better than the...
16,038
the previously described process seems to be good we have described the validation part of the process but we haven' touched on the cross part of it so where is the cross-validationto understand that intricacy of the cv processwe would have to discuss why we need this in the first place the need for it arises from the ...
16,039
 eave one out cv in this strategy for cross validationwe select random single data point from the initial training dataset and that becomes our validation set so we have single point only in our validation set and the rest - observations become our training set this means that if have data points in training set than ...
16,040
in scikit-learngrid search can be done using the gridsearchcv class we go through an example by performing grid search on support vector machine (svmmodel on the breast cancer dataset from earlier the svm model is another example of supervised machine learning algorithm that can be used for classification it is an exam...
16,041
grid_parameters {'kernel'['linear''rbf']'gamma'[ - - ]' '[ ]perform hyperparameter tuning print("tuning hyper-parameters for accuracy\ "clf gridsearchcv(svc(random_state= )grid_parameterscv= scoring='accuracy'clf fit(x_trainy_trainview accuracy scores for all the models print("grid scores for all the models based on cv...
16,042
figure - model performance metrics for tuned svm model on the breast cancer dataset well things are certainly looking great nowour model gives an overall score and model accuracy of on the test dataset tooas depicted in figure - this should give you clear indication of the power of hyperparameter tuningthis scheme of t...
16,043
get best modelpredict and evaluate performance rs_best random_search best_estimator_ rs_y_pred rs_best predict(x_testmeu get_metrics(true_labels=y_testpredicted_labels=rs_y_predaccuracy precision recall score in this examplewe are getting the values of parameter and gamma from an exponential distribution and we are con...
16,044
while the simplest approach to having models that are interpretable is to use algorithms that lead to interpretable models like decision treeslogistic regression and others but we don' have the guarantee that an interpretable model will provide us with the best performance hence we cannot always resort to such models r...
16,045
besides thissincethe time this project startedthey have committed some improvementsnamely support for regression back into the original lime repository and they still have other aspects of interpretation in their roadmap and further improvements to lime in the future you can easily install skater by running the pip ins...
16,046
the general workflow within the skater package is to create an interpretation objectcreate model objectand run interpretation algorithms alsoan interpretation object takes as inputa datasetand optionally some metadata like feature names and row identifiers internallythe interpretation object will generate datamanager t...
16,047
once this is completewe are ready to run model interpretation algorithms we will start by trying to generate feature importances this will give us an idea of the degree to which our predictive model relies on particular features the skater framework' feature importance implementation is based on an information theory c...
16,048
figure - one-way partial dependence plot for our logistic regression model predictor based on worst area from the plot in figure - we can see that the worst area feature has strong influence on the model decision making process based on the plotif the worst area value decreases from the model is more prone to classify ...
16,049
figure - model interpretation for our logistic regression model' prediction for data point having no cancer (benignthe results depicted in figure - show the features that were primarily responsible for the model to predict the data point as label having no cancer we can also see the feature that was the most influentia...
16,050
the results depicted in figure - once again show us the features that were primarily responsible for the model to predict the data point as label having malignant cancer the feature worst area was again the most influential one and you can notice the stark difference in its value as compared to the previous data point ...
16,051
this code will persist our model on the disk as file named lr_model pkl so whenever we will load this object in memory again we will get the logistic regression model object lr joblib load('lr_model pkl'lr logisticregression( = class_weight=nonedual=falsefit_intercept=trueintercept_scaling= max_iter= multi_class='ovr'n...
16,052
model deployment as service the computational world is seeing surge of the cloud and the xaas (anything as servicemodel in all areas this is also true for model development and deployment major providers like googlemicrosoftand amazon web services (awsprovide the facility of developing machine learning models using th...
16,053
real-world case studies
16,054
analyzing bike sharing trends "all work and no playis well-known proverb and we certainly do not want to be dull so farwe have covered the theoretical conceptsframeworksworkflowsand tools required to solve data science problems the use case driven theme begins with this in this section of the bookwe cover wide range of...
16,055
problem statement with environmental issues and health becoming trending topicsusage of bicycles as mode of transportation has gained traction in recent years to encourage bike usagecities across the world have successfully rolled out bike sharing programs under such schemesriders can rent bicycles using manualautomate...
16,056
figure - sample rows from bike sharing dataset the data seems to have loaded correctly nextwe need to check what data types pandas has inferred and if any of the attributes require type conversions the following snippet helps us check the data types of all attributes in [ ]hour_df dtypes out[ ]instant int dteday object...
16,057
now that we have attribute names cleaned upwe perform type-casting of attributes using utilities like pd to_datetime(and astype(the following snippet gets the attributes into proper data types in [ ]date time conversion hour_df['datetime'pd to_datetime(hour_df datetimecategorical variables hour_df['season'hour_df seaso...
16,058
similarlydistribution of ridership across days of the week also presents interesting trends of higher usage during afternoon hours over weekendswhile weekdays see higher usage during mornings and evenings the code for the same is available in the jupyter notebook bike_sharing_eda ipynb the plot is as shown in figure - ...
16,059
we encourage you to try and plot the four seasons across different subplots as an exercise to employ plotting concepts and see the trends for each season separately moving up the aggregation levellet' look at the distribution at year level our dataset contains year value of representing and representing we use violin p...
16,060
in [ ]fig,(ax ,ax )plt subplots(ncols= sn boxplot(data=hour_df[['total_count''casual','registered']],ax=ax sn boxplot(data=hour_df[['temp','windspeed']],ax=ax the generated plot is shown in figure - we can easily mark out that for the three count related attributesall of them seem to have sizable number of outlier valu...
16,061
correlations correlation helps us understand relationships between different attributes of the data since this focuses on forecastingcorrelations can help us understand and exploit relationships to build better models ##note it is important to understand that correlation does not imply causation we strongly encourage y...
16,062
the two count variablesregistered and casualshow obvious strong correlation to total_count similarlytemp and atemp show high correlation wind_speed and humidity have slight negative correlation overallnone of the attributes show high correlational statistics regression analysis regression analysis is statistical model...
16,063
non-linear regressionin cases where dependent variable is related polynomially to independent variablei the regression function has independent variablespower of more than it is also termed as polynomial regression regression techniques may also be classified as non-parametric assumptions regression analysis has few g...
16,064
figure - normal plot ( - ploton the left and histogram to confirm normality on the right any deviation from the straight line in normal plot or skewness/multi-modality in histogram shows that the data does not pass the normality test  -squaredgoodness of fit -squared or the coefficient of determination is another meas...
16,065
the following snippet showcases the function to one hot encode categorical variablesbased on methodologies we discussed in detail in feature engineering and selection def fit_transform_ohe(df,col_name)"""this function performs one hot encoding for the specified column argsdf(pandas dataframe)the data frame containing t...
16,066
the following snippet loops through the list of categorical variables to transform and prepare list of encoded attributes in [ ]cat_attr_list ['season','is_holiday''weather_condition','is_workingday''hour','weekday','month','year'encoded_attr_list [for col in cat_attr_listreturn_obj fit_transform_ohe( ,colencoded_attr_...
16,067
if we think for secondwhat would best fitting line look likesuch line would invariably have the least error/residuali the difference between the predicted and observed would be least for such line the ordinary least squares criterion is one such technique to identify the best fitting line the algorithm tries to minimiz...
16,068
figure - residual plot the plot in figure - clearly violates the homoscedasticity assumptionwhich is about residuals being random and not following any pattern to further quantify our findings related to the modelwe plot the cross-validation scores we use the cross_val_score(function available again as part of the mode...
16,069
but before we can use the test dataset on the learned regression linewe need to make sure the attributes have been through the same preprocessing in both training and testing sets since we transformed categorical variables into their one hot encodings in the train datasetin the following snippet we perform the same act...
16,070
ax axhline(lw= ,color='black'ax set_xlabel('observed'ax set_ylabel('residuals'ax title set_text("residual plot with -squared={}format(np average( _score))plt show(the generated plot shows an -squared that is comparable to training performance the plot is shown in figure - figure - residual plot for test dataset it is c...
16,071
we explain the concepts and terminologies related to decision trees using an example suppose we have hypothetical dataset of car models from different manufacturers assume each data point has features like fuel_capacityengine_capacitypriceyear_of_purchasemiles_drivenand mileage given this datawe need model that can pre...
16,072
mean absolute errorused for regression treesit is similar to mse though we only use the difference between the observed and predicted values variance reductionthis was first introduced with cart algorithmand it uses the standard formula of variance and we choose the split that results in least variance gini impurity/in...
16,073
training similar to the process with linear regressionwe will use the same preprocessed dataframe train_df_new with categoricals transformed into one hot encoded form along with other numerical attributes we also split the dataset into train and test again using the train_test_split(utility from scikit-learn the traini...
16,074
figure - decision tree with defined hyperparameters on bike sharing dataset now we start with the actual training process as must be evident from our workflow so farwe would train our regressor using -fold cross validation since we have hyperparameters as well in case of decision trees to worrywe need method to fine-tu...
16,075
the grid search of hyperparameters with -fold cross validation is an iterative process wrappedoptimizedand standardized by gridsearchcv(function the training process takes time due to the same and results in quite few useful attributes to analyze the best_score_ attribute helps us get the best cross validation score ou...
16,076
the output shows sudden improvement in score as depth increases from to while gradual improvement as we reach from the impact of number of leaf nodes is rather interesting the difference in scores between and leaf nodes is strikingly not much this is clear indicator that further finetuning is possible figure - depicts ...
16,077
next steps decision trees helped us achieve better performance over linear regression based modelsyet there are improvements possible the following are few next steps to ponder and keep in mindmodel fine-tuningwe achieved drastic improvement from using decision treesyet this can be improved further by analyzing the res...
16,078
analyzing movie reviews sentiment in this we continue with our focus on case-study oriented where we will focus on specific real-world problems and scenarios and how we can use machine learning to solve them we will cover aspects pertaining to natural language processing (nlp)text analyticsand machine learning in this ...
16,079
besides looking at various approaches and modelswe also focus on important aspects in the machine learning pipeline including text pre-processingnormalizationand in-depth analysis of modelsincluding model interpretation and topic models the key idea here is to understand how we tackle problem like sentiment analysis on...
16,080
we also use our custom developed text pre-processing and normalization modulewhich you will find in the files named contractions py and text_normalizer py utilities related to supervised model fittingpredictionand evaluation are present in model_evaluation_utils pyso make sure you have these modules in the same directo...
16,081
stemming and lemmatizationword stems are usually the base form of possible words that can be created by attaching affixes like prefixes and suffixes to the stem to create new words this is known as inflection the reverse process of obtaining the base form of word is known as stemming simple example are the words watche...
16,082
lemmatize text if text_lemmatizationdoc lemmatize_text(docremove special characters if special_char_removaldoc remove_special_characters(docremove extra whitespace doc re sub(+''docremove stopwords if stopword_removaldoc remove_stopwords(docis_lower_case=text_lower_casenormalized_corpus append(docreturn normalized_corp...
16,083
now that we have our normalization module readywe can start modeling and analyzing our corpus nlp and text analytics enthusiasts who might be interested in more in-depth details of text normalization can refer to the section "text normalization,page of text analytics with python (apressdipanjan sarkar unsupervised lex...
16,084
nowwe can load our imdb review datasetsubset out the last , reviews which will be used for our analysisand normalize them using the following snippet in [ ]dataset pd read_csv( 'movie_reviews csv'reviews np array(dataset['review']sentiments np array(dataset['sentiment']extract data for model evaluation test_reviews rev...
16,085
pattern lexicon the pattern package is complete natural language processing framework available in python which can be used for text processingsentiment analysis and more this has been developed by clips (computational linguistics psycholinguistics) research center associated with the linguistics department of the facu...
16,086
predicted sentiment polarity- reviewi don' care if some people voted this movie to be bad if you want the truth this is very good movieit has every thing movie should have you really should get this one actual sentimentpositive predicted sentiment polarity reviewworst horror film ever but funniest film ever rolled in o...
16,087
sentiwordnet lexicon the wordnet corpus is definitely one of the most popular corpora for the english language used extensively in natural language processing and semantic analysis wordnet gave us the concept of synsets or synonym sets the sentiwordnet lexicon is based on wordnet synsets and can be used for sentiment ...
16,088
aggregate final scores final_score pos_score neg_score norm_final_score round(float(final_scoretoken_count final_sentiment 'positiveif norm_final_score > else 'negativeif verbosenorm_obj_score round(float(obj_scoretoken_count norm_pos_score round(float(pos_scoretoken_count norm_neg_score round(float(neg_scoretoken_coun...
16,089
actual sentimentpositive sentiment statspredicted sentiment objectivity positive negative overall positive we can clearly see the predicted sentiment along with sentiment polarity scores and an objectivity score for each sample movie review depicted in formatted dataframes let' use this model now to predict the sentime...
16,090
:- [- - - - - - - - - : [ terrorizing - [- - - - - - - - - - thankful [ each line in the preceding lexicon sample depicts unique termwhich can either be an emoticon or word the first token indicates the word/emoticonthe second token indicates the mean sentiment polarity scorethe third token indicates the standard devia...
16,091
for aggregated polarity > neutral between [- ]and negative for polarity - we use threshold of > for positive and for negative in our corpus the following is the analysis of our sample reviews in [ ]for reviewsentiment in zip(test_reviews[sample_review_ids]test_ sentiments[sample_review_ids])print('review:'reviewprint('...
16,092
we get an overall -score and model accuracy of %which is quite similar to the afinn based model the afinn based model only wins out on the average precision by %otherwiseboth models have similar performance classifying sentiment with supervised learning another way to build model to understand the text content and pred...
16,093
in our scenariodocuments indicate the movie reviews and classes indicate the review sentiments that can either be positive or negativemaking it binary classification problem we will build models using both traditional machine learning methods and newer deep learning in the subsequent sections you can refer to the pytho...
16,094
in [ ]from sklearn feature_extraction text import countvectorizertfidfvectorizer build bow features on train reviews cv countvectorizer(binary=falsemin_df= max_df= ngram_range=( , )cv_train_features cv fit_transform(norm_train_reviewsbuild tfidf features on train reviews tv tfidfvectorizer(use_idf=truemin_df= max_df= n...
16,095
gradient descent (refer to the section"the three stages of logistic regressionin if you are interested in more detailslogistic regression is also popularly known as logit regression or maxent (maximum entropyclassifier we will now use our utility function train_predict_modelfrom our model_evaluation_utils module to bui...
16,096
we get an overall -score and model accuracy of %depicted in figure - which is great but our previous model is still slightly better you can similarly use the support vector machine model estimator object svmwhich we created earlierand use the same snippet to train and predict using an svm model we obtained maximum accu...
16,097
sample test label transformationactual labels['negative'positive'negative'encoded labels[ one hot encoded labels[ ]thuswe can see from the preceding sample outputs how our sentiment class labels have been encoded into numeric representationswhich in turn have been converted into one-hot encoded vectors the feature engi...
16,098
in [ ]generate averaged word vector features from word vec model avg_wv_train_features averaged_word vec_vectorizer(corpus=tokenized_trainmodel= v_modelnum_features= avg_wv_test_features averaged_word vec_vectorizer(corpus=tokenized_testmodel= v_modelnum_features= the glove modelwhich stands for global vectorsis an uns...
16,099
figure - fully connected deep neural network model for sentiment classification we call this fully connected deep neural network (dnnbecause neurons or units in each pair of adjacent layers are fully pairwise connected these networks are also known as deep artificial neural networks (annsor multi-layer perceptrons (mlp...