id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
17,200 | ting the number of clusters to --the text to the left shows the index of the cluster and the total number of points in the cluster herethe clustering seems to have picked up on "dark skinned and smiling,"collared shirt,"smiling woman,"hussein,and "high forehead we could also find these highly similar clusters using the... |
17,201 | this introduced range of unsupervised learning algorithms that can be applied for exploratory data analysis and preprocessing having the right representation of the data is often crucial for supervised or unsupervised learning to succeedand preprocessing and decomposition methods play an important part in data preparat... |
17,202 | let' briefly review the api that we introduced in and all algorithms in scikit-learnwhether preprocessingsupervised learningor unsupervised learning algorithmsare implemented as classes these classes are called estimators in scikitlearn to apply an algorithmyou first have to instantiate an object of the particular clas... |
17,203 | representing data and engineering features so farwe've assumed that our data comes in as two-dimensional array of floatingpoint numberswhere each column is continuous feature that describes the data points for many applicationsthis is not how the data is collected particularly common type of feature is the categorical ... |
17,204 | the right way can have bigger influence on the performance of supervised model than the exact parameters you choose in this we will first go over the important and very common case of categorical featuresand then give some examples of helpful transformations for specific combinations of features and models categorical ... |
17,205 | data we know from that logistic regression makes predictionsyusing the following formulay [ [ [ [ [px[pb where [iand are coefficients learned from the training set and [iare the input features this formula makes sense when [iare numbersbut not when [ is "mastersor "bachelorsclearly we need to represent our data in some... |
17,206 | the dummy encoding used in statistics for simplicitywe encode each category with different binary feature in statisticsit is common to encode categorical feature with different possible values into - features (the last one is represented as all zerosthis is done to simplify the analysis (more technicallythis will avoid... |
17,207 | check the contents of column is using the value_counts function of pandas series (the type of single column in dataframe)to show us what the unique values are and how often they appearin[ ]print(data gender value_counts()out[ ]male female namegenderdtypeint we can see that there are exactly two values for gender in thi... |
17,208 | while the categorical features were expanded into one new feature for each possible valuein[ ]data_dummies head(out[ ]age hoursworkclass_ perweek workclass_ workclass_ federallocal-gov gov occupation_ techsupport occupation_ income_ income_ transport moving rows columns we can now use the values attribute to convert th... |
17,209 | shape( shape( ,now the data is represented in way that scikit-learn can work withand we can proceed as usualin[ ]from sklearn linear_model import logisticregression from sklearn model_selection import train_test_split x_trainx_testy_trainy_test train_test_split(xyrandom_state= logreg logisticregression(logreg fit(x_tra... |
17,210 | in the example of the adult datasetthe categorical variables were encoded as strings on the one handthat opens up the possibility of spelling errorsbut on the other handit clearly marks variable as categorical oftenwhether for ease of storage or because of the way the data is collectedcategorical variables are encoded ... |
17,211 | categorical feature integer feature socks fox socks box using get_dummies will only encode the string feature and will not change the integer featureas you can see in table - in[ ]pd get_dummies(demo_dftable - one-hot-encoded version of the data from table - leaving the integer feature unchanged integer feature categor... |
17,212 | the best way to represent data depends not only on the semantics of the databut also on the kind of model you are using linear models and tree-based models (such as decision treesgradient boosted treesand random forests)two large and very commonly used familieshave very different properties when it comes to how they wo... |
17,213 | we imagine partition of the input range for the feature (in this casethe numbers from - to into fixed number of bins--say data point will then be represented by which bin it falls into to determine thiswe first have to define the bins in this casewe'll define bins equally spaced between - and we use the np linspace fun... |
17,214 | which_bin np digitize(xbins=binsprint("\ndata points:\ " [: ]print("\nbin membership for data points:\ "which_bin[: ]out[ ]data points[[- [- ]bin membership for data points[ [ ]what we did here is transform the single continuous input feature in the wave dataset into categorical feature that encodes which bin data poin... |
17,215 | print("x_binned shape{}format(x_binned shape)out[ ]x_binned shape( now we build new linear regression model and new decision tree model on the one-hot-encoded data the result is visualized in figure - together with the bin boundariesshown as dotted black linesin[ ]line_binned encoder transform(np digitize(linebins=bins... |
17,216 | regression model and the decision tree make exactly the same predictions for each binthey predict constant value as features are constant within each binany model must predict the same value for all points within bin comparing what the models learned before binning the features and afterwe see that the linear model bec... |
17,217 | plt ylabel("regression output"plt xlabel("input feature"plt plot( [: ] ' ' =' 'figure - linear regression using binned features and single global slope in this examplethe model learned an offset for each bintogether with slope the learned slope is downwardand shared across all the bins--there is single -axis featurewhi... |
17,218 | within the binand zero everywhere else figure - shows the result of the linear model on this new representationin[ ]reg linearregression(fit(x_productyline_product np hstack([line_binnedline line_binned]plt plot(linereg predict(line_product)label='linear regression product'for bin in binsplt plot([binbin][- ]':' =' 'pl... |
17,219 | nomials of the original features for given feature xwe might want to consider * * * and so on this is implemented in polynomialfeatures in the preprocessing modulein[ ]from sklearn preprocessing import polynomialfeatures include polynomials up to * the default "include_bias=trueadds feature that' constantly poly polyno... |
17,220 | print("polynomial feature names:\ {}format(poly get_feature_names())out[ ]polynomial feature names[' '' ^ '' ^ '' ^ '' ^ '' ^ '' ^ '' ^ '' ^ '' ^ 'you can see that the first column of x_poly corresponds exactly to xwhile the other columns are the powers of the first entry it' interesting to see how large some of the va... |
17,221 | data howeverpolynomials of high degree tend to behave in extreme ways on the boundaries or in regions with little data as comparisonhere is kernel svm model learned on the original datawithout any transformation (see figure - )in[ ]from sklearn svm import svr for gamma in [ ]svr svr(gamma=gammafit(xyplt plot(linesvr pr... |
17,222 | boston housing dataset we already used polynomial features on this dataset in now let' have look at how these features were constructedand at how much the polynomial features help first we load the dataand rescale it to be between and using minmaxscalerin[ ]from sklearn datasets import load_boston from sklearn model_se... |
17,223 | ' '' '' ^ '' '' '' '' '' '' '' '' '' '' '' ^ '' '' '' '' '' '' '' '' '' '' ^ '' '' '' '' '' '' '' '' '' ^ '' '' '' '' '' '' '' '' ^ '' '' '' '' '' '' '' ^ '' '' '' '' '' '' ^ '' '' '' '' '' ^ '' '' '' '' ^ '' '' '' ^ '' '' ^ 'the first new feature is constant featurecalled " here the next features are the original feat... |
17,224 | performance of ridge adding interactions and polynomials actually decreases performance slightly univariate nonlinear transformations we just saw that adding squared or cubed features can help linear models for regression there are other transformations that often prove useful for transforming certain featuresin partic... |
17,225 | print("number of feature appearances:\ {}format(np bincount( [: ]))out[ ]number of feature appearances[ the value seems to be the most commonwith appearances (bincount always starts at )and the counts for higher values fall quickly howeverthere are some very high valueslike appearing twice we visualize the counts in fi... |
17,226 | values (many small ones and few very large onesis very common in practice howeverit is something most linear models can' handle very well let' try to fit ridge regression to this modelin[ ]from sklearn linear_model import ridge x_trainx_testy_trainy_test train_test_split(xyrandom_state= score ridge(fit(x_trainy_trainsc... |
17,227 | building ridge model on the new data provides much better fitin[ ]score ridge(fit(x_train_logy_trainscore(x_test_logy_testprint("test score{ }format(score)out[ ]test score finding the transformation that works best for each combination of dataset and model is somewhat of an art in this exampleall the features had the s... |
17,228 | have huge influence on how models perform on given dataset this is particularly true for less complex models like linear models and naive bayes models tree-based modelson the other handare often able to discover important interactions themselvesand don' require transforming the data explicitly most of the time other mo... |
17,229 | features to the data we expect the feature selection to be able to identify the features that are noninformative and remove themin[ ]from sklearn datasets import load_breast_cancer from sklearn feature_selection import selectpercentile from sklearn model_selection import train_test_split cancer load_breast_cancer(get d... |
17,230 | false true false true false false false false false false true false true false false false false true false true false false false false true true false true false false false falsefigure - features selected by selectpercentile as you can see from the visualization of the maskmost of the selected features are the orig... |
17,231 | coefficientswhich can also be used to capture feature importances by considering the absolute values as we saw in linear models with penalty learn sparse coefficientswhich only use small subset of features this can be viewed as form of feature selection for the model itselfbut can also be used as preprocessing step to ... |
17,232 | select featuressome of the noise features are also selected let' take look at the performancein[ ]x_test_l select transform(x_testscore logisticregression(fit(x_train_l y_trainscore(x_test_l y_testprint("test score{ }format(score)out[ ]test score with the better feature selectionwe also gained some improvements here it... |
17,233 | classifier model the feature selection got better compared to the univariate and model-based selectionbut one feature was still missed running this code also takes significantly longer than that for the model-based selectionbecause random forest model is trained timesonce for each feature that is dropped let' test the ... |
17,234 | feature engineering is often an important place to use expert knowledge for particular application while the purpose of machine learning in many cases is to avoid having to create set of expert-designed rulesthat doesn' mean that prior knowledge of the application or domain should be discarded oftendomain experts can h... |
17,235 | print("citi bike data:\ {}format(citibike head())out[ ]citi bike datastarttime : : : : : : : : : : freq hnameonedtypefloat the following example shows visualization of the rental frequencies for the whole month (figure - )in[ ]plt figure(figsize=( )xticks pd date_range(start=citibike index min()end=citibike index max()... |
17,236 | daysas our training setand the remaining data pointscorresponding to the remaining daysas our test set the only feature that we are using in our prediction task is the date and time when particular number of rentals occurred sothe input feature is the date and time--say : : --and the output is the number of rentals in ... |
17,237 | makes this seem like good model to start with we use the posix time feature and pass random forest regressor to our eval_on_features function figure - shows the resultin[ ]from sklearn ensemble import randomforestregressor regressor randomforestregressor(n_estimators= random_state= plt figure(eval_on_features(xyregress... |
17,238 | x_hour citibike index hour reshape(- eval_on_features(x_houryregressorout[ ]test-set ^ figure - predictions made by random forest using only the hour of the day the is already much betterbut the predictions clearly miss the weekly pattern now let' also add the day of the week (see figure - )in[ ]x_hour_week np hstack([... |
17,239 | week and time of day it has an of and shows pretty good predictive performance what this model likely is learning is the mean number of rentals for each combination of weekday and time of day from the first days of august this actually does not require complex model like random forestso let' try with simpler modellinea... |
17,240 | eval_on_features(x_hour_week_onehotyridge()out[ ]test-set ^ figure - predictions made by linear regression using one-hot encoding of hour of day and day of week this gives us much better match than the continuous feature encoding now the linear model learns one coefficient for each day of the weekand one coefficient fo... |
17,241 | and hour of day features this transformation finally yields model that performs similarly well to the random forest big benefit of this model is that it is very clear what is learnedone coefficient for each day and time we can simply plot the coefficients learned by the modelsomething that would not be possible for the... |
17,242 | summary and outlook in this we discussed how to deal with different data types (in particularwith categorical variableswe emphasized the importance of representing data in way that is suitable for the machine learning algorithm--for exampleby one-hotencoding categorical variables we also discussed the importance of eng... |
17,243 | model evaluation and improvement having discussed the fundamentals of supervised and unsupervised learningand having explored variety of machine learning algorithmswe will now dive more deeply into evaluating models and selecting parameters we will focus on the supervised methodsregression and classificationas evaluati... |
17,244 | ested in measuring how well our model generalizes to newpreviously unseen data we are not interested in how well our model fit the training setbut rather in how well it can make predictions for data that was not observed during training in this we will expand on two aspects of this evaluation we will first introduce cr... |
17,245 | cross-validation is implemented in scikit-learn using the cross_val_score function from the model_selection module the parameters of the cross_val_score function are the model we want to evaluatethe training dataand the ground-truth labels let' evaluate logisticregression on the iris datasetin[ ]from sklearn model_sele... |
17,246 | there are several benefits to using cross-validation instead of single split into training and test set firstremember that train_test_split performs random split of the data imagine that we are "luckywhen randomly splitting the dataand all examples that are hard to classify end up in the training set in that casethe te... |
17,247 | from sklearn datasets import load_iris iris load_iris(print("iris labels:\ {}format(iris target)out[ ]iris labels[ as you can seethe first third of the data is the class the second third is the class and the last third is the class imagine doing three-fold cross-validation on this dataset the first fold would be only c... |
17,248 | belong to class bthen stratified cross-validation ensures that in each fold of samples belong to class and of samples belong to class it is usually good idea to use stratified -fold cross-validation instead of -fold cross-validation to evaluate classifierbecause it results in more reliable estimates of generalization p... |
17,249 | kfold kfold(n_splits= print("cross-validation scores:\ {}formatcross_val_score(logregiris datairis targetcv=kfold))out[ ]cross-validation scores remembereach fold corresponds to one of the classes in the iris datasetand so nothing can be learned another way to resolve this problem is to shuffle the data instead of stra... |
17,250 | anothervery flexible strategy for cross-validation is shuffle-split cross-validation in shuffle-split cross-validationeach split samples train_size many points for the training set and test_size many (disjointpoint for the test set this splitting is repeated n_iter times figure - illustrates running four iterations of ... |
17,251 | another very common setting for cross-validation is when there are groups in the data that are highly related say you want to build system to recognize emotions from pictures of facesand you collect dataset of pictures of people where each person is captured multiple timesshowing various emotions the goal is to build c... |
17,252 | entirely in the test setin[ ]mglearn plots plot_label_kfold(figure - label-dependent splitting with groupkfold there are more splitting strategies for cross-validation in scikit-learnwhich allow for an even greater variety of use cases (you can find these in the scikit-learn user guidehoweverthe standard kfoldstratifie... |
17,253 | svc( = gamma= svc( = gamma= svc( = gamma= gamma= svc( = gamma= svc( = gamma= svc( = gamma= gamma= svc( = gamma= svc( = gamma= svc( = gamma= simple grid search we can implement simple grid search just as for loops over the two parameterstraining and evaluating classifier for each combinationin[ ]naive grid search implem... |
17,254 | carry over to new data because we used the test data to adjust the parameterswe can no longer use it to assess how good the model is this is the same reason we needed to split the data into training and test sets in the first placewe need an independent dataset to evaluateone that was not used to create the model one w... |
17,255 | and evaluate it on the test set svm svc(**best_parameterssvm fit(x_trainvaly_trainvaltest_score svm score(x_testy_testprint("best score on validation set{ }format(best_score)print("best parameters"best_parametersprint("test set score with best parameters{ }format(test_score)out[ ]size of training set size of validation... |
17,256 | for gamma in [ ]for in [ ]for each combination of parameterstrain an svc svm svc(gamma=gammac=cperform cross-validation scores cross_val_score(svmx_trainvaly_trainvalcv= compute mean cross-validation accuracy score np mean(scoresif we got better scorestore the score and parameters if score best_scorebest_score score be... |
17,257 | rithm on specific dataset howeverit is often used in conjunction with parameter search methods like grid search for this reasonmany people use the term cross-validation colloquially to refer to grid search with cross-validation the overall process of splitting the datarunning the grid searchand evaluating the final par... |
17,258 | grid to search (param_grid)and the cross-validation strategy we want to use (sayfive-fold stratified cross-validation)in[ ]from sklearn model_selection import gridsearchcv from sklearn svm import svc grid_search gridsearchcv(svc()param_gridcv= gridsearchcv will use cross-validation in place of the split into training a... |
17,259 | over the different splits for this parameter settingis stored in best_score_in[ ]print("best parameters{}format(grid_search best_params_)print("best cross-validation score{ }format(grid_search best_score_)out[ ]best parameters{' ' 'gamma' best cross-validation score againbe careful not to confuse best_score_ with the g... |
17,260 | after converting it to pandas dataframein[ ]import pandas as pd convert to dataframe results pd dataframe(grid_search cv_results_show the first rows display(results head()out[ ] param_c param_gamma rank_test_score split _test_score params {' ' 'gamma' {' ' 'gamma' {' ' 'gamma' {' ' 'gamma' {' ' 'gamma' split _test_scor... |
17,261 | each point in the heat map corresponds to one run of cross-validationwith particular parameter setting the color encodes the cross-validation accuracywith light colors meaning high accuracy and dark colors meaning low accuracy you can see that svc is very sensitive to the setting of the parameters for many of the param... |
17,262 | figaxes plt subplots( figsize=( )param_grid_linear {' 'np linspace( )'gamma'np linspace( )param_grid_one_log {' 'np linspace( )'gamma'np logspace(- )param_grid_range {' 'np logspace(- )'gamma'np logspace(- - )for param_gridax in zip([param_grid_linearparam_grid_one_logparam_grid_range]axes)grid_search gridsearchcv(svc(... |
17,263 | to use search over spaces that are not grids in some casestrying all possible combinations of all parameters as gridsearchcv usually doesis not good idea for examplesvc has kernel parameterand depending on which kernel is chosenother parameters will be relevant if ker nel='linear'the model is linearand only the paramet... |
17,264 | variedin[ ]results pd dataframe(grid_search cv_results_we display the transposed table so that it better fits on the pagedisplay(results tout[ ]param_c param_gamma nan nan nan nan param_kernel rbf rbf rbf rbf linear linear linear linear params { kernelrbfgamma { kernelrbfgamma { kernelrbfgamma { { kernelrbfkernelgamma ... |
17,265 | which might make our results unstable and make us depend too much on this single split of the data we can go step furtherand instead of splitting the original data into training and test sets onceuse multiple splits of cross-validation this will result in what is called nested cross-validation in nested cross-validatio... |
17,266 | def nested_cv(xyinner_cvouter_cvclassifierparameter_grid)outer_scores [for each split of the data in the outer cross-validation (split method returns indicesfor training_samplestest_samples in outer_cv split(xy)find best parameter using inner cross-validation best_parms {best_score -np inf iterate over parameters for p... |
17,267 | be done completely independently from the other parameter settings and models this makes grid search and cross-validation ideal candidates for parallelization over multiple cpu cores or over cluster you can make use of multiple cores in grid searchcv and cross_val_score by setting the n_jobs parameter to the number of ... |
17,268 | decreasing the number of hospital admissions it could also be getting more users for your websiteor having users spend more money in your shop when choosing model or adjusting parametersyou should pick the model or parameter values that have the most positive influence on the business metric often this is hardas assess... |
17,269 | patient will undergo additional screening herewe would call positive test (an indication of cancerthe positive classand negative test the negative class we can' assume that our model will always work perfectlyand it will make mistakes for any applicationwe need to ask ourselves what the consequences of these mistakes m... |
17,270 | machine learning modelby always predicting "no click on the other handeven with imbalanced dataa accurate model could in fact be quite good howeveraccuracy doesn' allow us to distinguish the constant "no clickmodel from potentially good model to illustratewe'll create : imbalanced dataset from the digits datasetby clas... |
17,271 | constant predictor this could indicate either that something is wrong with how we used decisiontreeclassifieror that accuracy is in fact not good measure here for comparison purposeslet' evaluate two more classifierslogisticregression and the default dummyclassifierwhich makes random predictions but produces classes wi... |
17,272 | from sklearn metrics import confusion_matrix confusion confusion_matrix(y_testpred_logregprint("confusion matrix:\ {}format(confusion)out[ ]confusion matrix[[ ]the output of confusion_matrix is two-by-two arraywhere the rows correspond to the true classes and the columns correspond to the predicted classes each entry c... |
17,273 | cationswhile other entries tell us how many samples of one class got mistakenly classified as another class if we declare " ninethe positive classwe can relate the entries of the confusion matrix with the terms false positive and false negative that we introduced earlier to complete the picturewe call correctly classif... |
17,274 | most frequent class[[ ]dummy model[[ ]decision tree[[ ]logistic regression [[ ]looking at the confusion matrixit is quite clear that something is wrong with pred_most_frequentbecause it always predicts the same class pred_dummyon the other handhas very small number of true positives ( )particularly compared to the numb... |
17,275 | tp tp+fp precision is used as performance metric when the goal is to limit the number of false positives as an exampleimagine model for predicting whether new drug will be effective in treating disease in clinical trials clinical trials are notoriously expensiveand pharmaceutical company will only want to run an experi... |
17,276 | into accountit can be better measure than accuracy on imbalanced binary classification datasets let' run it on the predictions for the "nine vs restdataset that we computed earlier herewe will assume that the "nineclass is the positive class (it is labeled as true while the rest is labeled as false)so the positive clas... |
17,277 | precision recall -score support not nine nine avg total the classification_report function produces one line per class (heretrue and falseand reports precisionrecalland -score with this class as the positive class beforewe assumed the minority "nineclass was the positive class if we change the positive class to "not ni... |
17,278 | models and very good model are not as clear any more picking which class is declared the positive class has big impact on the metrics while the -score for the dummy classification is (vs for the logistic regressionon the "nineclassfor the "not nineclass it is vs which both seem like reasonable results looking at all th... |
17,279 | threshold we can use the classification_report function to evaluate precision and recall for both classesin[ ]print(classification_report(y_testsvc predict(x_test))out[ ]precision recall -score support avg total for class we get fairly small recalland precision is mixed because class is so much largerthe classifier foc... |
17,280 | y_pred_lower_threshold svc decision_function(x_test let' look at the classification report for this predictionin[ ]print(classification_report(y_testy_pred_lower_threshold)out[ ]precision recall -score support avg total as expectedthe recall of class went upand the precision went down we are now classifying larger regi... |
17,281 | as we just discussedchanging the threshold that is used to make classification decision in model is way to adjust the trade-off of precision and recall for given classifier maybe you want to miss less than of positive samplesmeaning desired recall of this decision depends on the applicationand it should be driven by bu... |
17,282 | each point along the curve in figure - corresponds to possible threshold of the decision_function we can seefor examplethat we can achieve recall of at precision of about the black circle marks the point that corresponds to threshold of the default threshold for decision_function this point is the trade-off that is cho... |
17,283 | from sklearn ensemble import randomforestclassifier rf randomforestclassifier(n_estimators= random_state= max_features= rf fit(x_trainy_trainrandomforestclassifier has predict_probabut not decision_function precision_rfrecall_rfthresholds_rf precision_recall_curvey_testrf predict_proba(x_test)[: ]plt plot(precisionreca... |
17,284 | print(" _score of random forest{ }formatf _score(y_testrf predict(x_test)))print(" _score of svc{ }format( _score(y_testsvc predict(x_test)))out[ ] _score of random forest _score of svc comparing two precision-recall curves provides lot of detailed insightbut is fairly manual process for automatic model comparisonwe mi... |
17,285 | the false positive rate (fpragainst the true positive rate (tprrecall that the true positive rate is simply another name for recallwhile the false positive rate is the fraction of false positives out of all negative samplesfpr fp fp+tn the roc curve can be computed using the roc_curve function (see figure - )in[ ]from ... |
17,286 | figure - in[ ]from sklearn metrics import roc_curve fpr_rftpr_rfthresholds_rf roc_curve(y_testrf predict_proba(x_test)[: ]plt plot(fprtprlabel="roc curve svc"plt plot(fpr_rftpr_rflabel="roc curve rf"plt xlabel("fpr"plt ylabel("tpr (recall)"plt plot(fpr[close_zero]tpr[close_zero]' 'markersize= label="threshold zero svc"... |
17,287 | from sklearn metrics import roc_auc_score rf_auc roc_auc_score(y_testrf predict_proba(x_test)[: ]svc_auc roc_auc_score(y_testsvc decision_function(x_test)print("auc for random forest{ }format(rf_auc)print("auc for svc{ }format(svc_auc)out[ ]auc for random forest auc for svc comparing the random forest and svm using the... |
17,288 | gamma gamma gamma accuracy accuracy accuracy auc auc auc figure - comparing roc curves of svms with different settings of gamma the accuracy of all three settings of gamma is the same this might be the same as chance performanceor it might not looking at the auc and the corresponding curvehoweverwe see clear distinctio... |
17,289 | of correctly classified examples and againwhen classes are imbalancedaccuracy is not great evaluation measure imagine three-class classification problem with of points belonging to class belonging to class band belonging to class what does being accurate mean on this datasetin generalmulticlass classification results a... |
17,290 | for the first classthe digit there are samples in the classand all of these samples were classified as class (there are no false negatives for class we can see that because all other entries in the first row of the confusion matrix are we can also see that no other digits were mistakenly classified as because all other... |
17,291 | sions with this class for class on the other handprecision is because no other class was mistakenly classified as while for class there are no false negativesso the recall is we can also see that the model has particular difficulties with classes and the most commonly used metric for imbalanced datasets in the multicla... |
17,292 | we have discussed many evaluation methods in detailand how to apply them given the ground truth and model howeverwe often want to use metrics like auc in model selection using gridsearchcv or cross_val_score luckily scikit-learn provides very simple way to achieve thisvia the scoring argument that can be used in both g... |
17,293 | grid-search with accuracy best parameters{'gamma' best cross-validation score (accuracy)) test set auc test set accuracy in[ ]using auc scoring insteadgrid gridsearchcv(svc()param_grid=param_gridscoring="roc_auc"grid fit(x_trainy_trainprint("\ngrid-search with auc"print("best parameters:"grid best_params_print("best cr... |
17,294 | from sklearn metrics scorer import scorers print("available scorers:\ {}format(sorted(scorers keys()))out[ ]available scorers['accuracy''adjusted_rand_score''average_precision'' '' _macro'' _micro'' _samples'' _weighted''log_loss''mean_absolute_error''mean_squared_error''median_absolute_error''precision''precision_macr... |
17,295 | ric accordingly the model evaluation and selection techniques we have described so far are the most important tools in data scientist' toolbox grid search and cross-validation as we've described them in this can only be applied to single supervised model we have seen beforehoweverthat many models require preprocessinga... |
17,296 | algorithm chains and pipelines for many machine learning algorithmsthe particular representation of the data that you provide is very importantas we discussed in this starts with scaling the data and combining features by hand and goes all the way to learning features using unsupervised machine learningas we saw in con... |
17,297 | rescale the training data x_train_scaled scaler transform(x_trainsvm svc(learn an svm on the scaled training data svm fit(x_train_scaledy_trainscale the test data and score the scaled data x_test_scaled scaler transform(x_testprint("test score{ }format(svm score(x_test_scaledy_test))out[ ]test score parameter selection... |
17,298 | new data (sayin form of our test set)this data will not have been used to scale the training dataand it might have different minimum and maximum than the training data the following example (figure - shows how the data processing during cross-validation and the final evaluation differin[ ]mglearn plots plot_improper_pr... |
17,299 | like any other model in scikit-learn the most common use case of the pipeline class is in chaining preprocessing steps (like scaling of the datatogether with supervised model like classifier building pipelines let' look at how we can use the pipeline class to express the workflow for training an svm after scaling the d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.