scikit-learn interview questions
13 questions with answers. 230 open jobs in India ask for scikit-learn.
what is the difference between 'transform' and 'fit_transform' in sklearn?
In scikit-learn estimator api,
fit(): used for generating learning model parameters from training datatransform(): parameters generated fromfit()method,applied upon model to generate transformed data set.fit_transform(): combination offit()andtransform()api on same data setCheckout Chapter-4 from this book & answer from stackexchange for more clarity
From Stack Overflow: asked by tqjustc, answered by Ronak Poriya (CC BY-SA 4.0)
How does the class_weight parameter in scikit-learn work?
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.
For how
class_weightworks: It penalizes mistakes in samples ofclass[i]withclass_weight[i]instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase theclass_weightof class 1 relative to class 0, say {0:.1, 1:.9}. If theclass_weightdoesn't sum to 1, it will basically change the regularization parameter.For how
class_weight="auto"works, you can have a look at this discussion. In the dev version you can useclass_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.From Stack Overflow: asked by kilgoretrout, answered by Andreas Mueller (CC BY-SA 3.0)
Can anyone explain me StandardScaler?
The idea behind
StandardScaleris that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).From Stack Overflow: asked by nitinvijay23, answered by user6903745 (CC BY-SA 4.0)
What are the pros and cons between get_dummies (Pandas) and OneHotEncoder (Scikit-learn)?
For machine learning, you almost definitely want to use
sklearn.OneHotEncoder. For other tasks like simple analyses, you might be able to usepd.get_dummies, which is a bit more convenient.Note that
sklearn.OneHotEncoderhas been updated in the latest version so that it does accept strings for categorical variables, as well as integers.The crux of it is that the
sklearnencoder creates a function which persists and can then be applied to new data sets which use the same categorical variables, with consistent results.from sklearn.preprocessing import OneHotEncoder # Create the encoder. encoder = OneHotEncoder(handle_unknown="ignore") encoder.fit(X_train) # Assume for simplicity all features are categorical. # Apply the encoder. X_train = encoder.transform(X_train) X_test = encoder.transform(X_test)Note how we apply the same encoder we created via
X_trainto the new data setX_test.Consider what happens if
X_testcontains different levels thanX_trainfor one of its variables. For example, let's sayX_train["color"]contains only"red"and"green", but in addition to those,X_test["color"]sometimes contains"blue".If we use
pd.get_dummies,X_testwill end up with an additional"color_blue"column whichX_traindoesn't have, and the inconsistency will probably break our code later on, especially if we are feedingX_testto ansklearnmodel which we trained onX_train.And if we want to process the data like this in production, where we're receiving a single example at a time,
pd.get_dummieswon't be of use.With
sklearn.OneHotEncoderon the other hand, once we've created the encoder, we can reuse it to produce the same output every time, with columns only for"red"and"green". And we can explicitly control what happens when it encounters the new level"blue": if we think that's impossible, then we can tell it to throw an error withhandle_unknown="error"; otherwise we can tell it to continue and simply set the red and green columns to 0, withhandle_unknown="ignore".From Stack Overflow: asked by O.rka, answered by Denziloe (CC BY-SA 4.0)
What is exactly sklearn.pipeline.Pipeline?
Transformer in scikit-learn - some class that have fit and transform method, or fit_transform method.
Predictor - some class that has fit and predict methods, or fit_predict method.
Pipeline is just an abstract notion, it's not some existing ml algorithm. Often in ML tasks you need to perform sequence of different transformations (find set of features, generate new features, select only some good features) of raw dataset before applying final estimator.
Here is a good example of Pipeline usage. Pipeline gives you a single interface for all 3 steps of transformation and resulting estimator. It encapsulates transformers and predictors inside, and now you can do something like:
vect = CountVectorizer() tfidf = TfidfTransformer() clf = SGDClassifier() vX = vect.fit_transform(Xtrain) tfidfX = tfidf.fit_transform(vX) predicted = clf.fit_predict(tfidfX) # Now evaluate all steps on test set vX = vect.fit_transform(Xtest) tfidfX = tfidf.fit_transform(vX) predicted = clf.fit_predict(tfidfX)With just:
pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SGDClassifier()), ]) predicted = pipeline.fit(Xtrain).predict(Xtrain) # Now evaluate all steps on test set predicted = pipeline.predict(Xtest)With pipelines you can easily perform a grid-search over set of parameters for each step of this meta-estimator. As described in the link above. All steps except last one must be transforms, last step can be transformer or predictor. Answer to edit: When you call
pipln.fit()- each transformer inside pipeline will be fitted on outputs of previous transformer (First transformer is learned on raw dataset). Last estimator may be transformer or predictor, you can call fit_transform() on pipeline only if your last estimator is transformer (that implements fit_transform, or transform and fit methods separately), you can call fit_predict() or predict() on pipeline only if your last estimator is predictor. So you just can't call fit_transform or transform on pipeline, last step of which is predictor.From Stack Overflow: asked by farhawa, answered by Ibraim Ganiev (CC BY-SA 3.0)
What are the different use cases of joblib versus pickle?
- joblib is usually significantly faster on large numpy arrays because it has a special handling for the array buffers of the numpy datastructure. To find about the implementation details you can have a look at the source code. It can also compress that data on the fly while pickling using zlib or lz4.
- joblib also makes it possible to memory map the data buffer of an uncompressed joblib-pickled numpy array when loading it which makes it possible to share memory between processes.
- if you don't pickle large numpy arrays, then regular pickle can be significantly faster, especially on large collections of small python objects (e.g. a large dict of str objects) because the pickle module of the standard library is implemented in C while joblib is pure python.
- since PEP 574 (Pickle protocol 5) has been merged in Python 3.8, it is now much more efficient (memory-wise and cpu-wise) to pickle large numpy arrays using the standard library. Large arrays in this context means 4GB or more.
- But joblib can still be useful with Python 3.8 to load objects that have nested numpy arrays in memory mapped mode with
mmap_mode="r".
From Stack Overflow: asked by msunbot, answered by ogrisel (CC BY-SA 4.0)
Why does one hot encoding improve machine learning performance?
Many learning algorithms either learn a single weight per feature, or they use distances between samples. The former is the case for linear models such as logistic regression, which are easy to explain.
Suppose you have a dataset having only a single categorical feature "nationality", with values "UK", "French" and "US". Assume, without loss of generality, that these are encoded as 0, 1 and 2. You then have a weight w for this feature in a linear classifier, which will make some kind of decision based on the constraint w×x + b > 0, or equivalently w×x < b.
The problem now is that the weight w cannot encode a three-way choice. The three possible values of w×x are 0, w and 2×w. Either these three all lead to the same decision (they're all < b or ≥b) or "UK" and "French" lead to the same decision, or "French" and "US" give the same decision. There's no possibility for the model to learn that "UK" and "US" should be given the same label, with "French" the odd one out.
By one-hot encoding, you effectively blow up the feature space to three features, which will each get their own weights, so the decision function is now w[UK]x[UK] + w[FR]x[FR] + w[US]x[US] < b, where all the x's are booleans. In this space, such a linear function can express any sum/disjunction of the possibilities (e.g. "UK or US", which might be a predictor for someone speaking English).
Similarly, any learner based on standard distance metrics (such as k-nearest neighbors) between samples will get confused without one-hot encoding. With the naive encoding and Euclidean distance, the distance between French and US is 1. The distance between US and UK is 2. But with the one-hot encoding, the pairwise distances between [1, 0, 0], [0, 1, 0] and [0, 0, 1] are all equal to √2.
This is not true for all learning algorithms; decision trees and derived models such as random forests, if deep enough, can handle categorical variables without one-hot encoding.
From Stack Overflow: asked by maheshakya, answered by Fred Foo (CC BY-SA 3.0)
RandomForestClassifier vs ExtraTreesClassifier in scikit learn
Yes both conclusions are correct, although the Random Forest implementation in scikit-learn makes it possible to enable or disable the bootstrap resampling.
In practice, RFs are often more compact than ETs. ETs are generally cheaper to train from a computational point of view but can grow much bigger. ETs can sometime generalize better than RFs but it's hard to guess when it's the case without trying both first (and tuning
n_estimators,max_featuresandmin_samples_splitby cross-validated grid search).From Stack Overflow: asked by denson, answered by ogrisel (CC BY-SA 3.0)
Recovering features names of explained_variance_ratio_ in PCA with scikit-learn
This information is included in the
pcaattribute:components_. As described in the documentation,pca.components_outputs an array of[n_components, n_features], so to get how components are linearly related with the different features, you have to:Note: Each coefficient represents the correlation between a particular pair of component and feature
import pandas as pd import pylab as pl from sklearn import datasets from sklearn.decomposition import PCA # Load dataset iris = datasets.load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) # Normalize data from sklearn import preprocessing data_scaled = pd.DataFrame(preprocessing.scale(df),columns = df.columns) # PCA pca = PCA(n_components=2) pca.fit_transform(data_scaled) # Dump components relations with features: print(pd.DataFrame(pca.components_,columns=data_scaled.columns,index = ['PC-1','PC-2']))Output:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) PC-1 0.522372 -0.263355 0.581254 0.565611 PC-2 -0.372318 -0.925556 -0.021095 -0.065416Important: As a side comment, note the PCA sign does not affect its interpretation since the sign does not affect the variance contained in each component. Only the relative signs of features forming the PCA dimension are important. In fact, if you run the PCA code again, you might get the PCA dimensions with the signs inverted. For an intuition about this, think about a vector and its negative in three-dimensional space. Both are essentially representing the same direction in space.
Check this post for further reference.
From Stack Overflow: asked by sereizam, answered by Rafa (CC BY-SA 4.0)
How to normalize a numpy array to a unit vector?
If you're using scikit-learn you can use
sklearn.preprocessing.normalize:import numpy as np from sklearn.preprocessing import normalize x = np.random.rand(1000)*10 norm1 = x / np.linalg.norm(x) norm2 = normalize(x[:,np.newaxis], axis=0).ravel() print np.all(norm1 == norm2) # TrueFrom Stack Overflow: asked by Donbeo, answered by ali_m (CC BY-SA 3.0)
Label encoding across multiple columns in scikit-learn
You can easily do this though,
df.apply(LabelEncoder().fit_transform)EDIT2:
In scikit-learn 0.20, the recommended way is
OneHotEncoder().fit_transform(df)as the OneHotEncoder now supports string input. Applying OneHotEncoder only to certain columns is possible with the ColumnTransformer.
EDIT:
Since this original answer is over a year ago, and generated many upvotes (including a bounty), I should probably extend this further.
For inverse_transform and transform, you have to do a little bit of hack.
from collections import defaultdict d = defaultdict(LabelEncoder)With this, you now retain all columns
LabelEncoderas dictionary.# Encoding the variable fit = df.apply(lambda x: d[x.name].fit_transform(x)) # Inverse the encoded fit.apply(lambda x: d[x.name].inverse_transform(x)) # Using the dictionary to label future data df.apply(lambda x: d[x.name].transform(x))MOAR EDIT:
Using Neuraxle's
FlattenForEachstep, it's possible to do this as well to use the sameLabelEncoderon all the flattened data at once:FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df)For using separate
LabelEncoders depending for your columns of data, or if only some of your columns of data needs to be label-encoded and not others, then using aColumnTransformeris a solution that allows for more control on your column selection and your LabelEncoder instances.From Stack Overflow: asked by Bryan, answered by Napitupulu Jon (CC BY-SA 4.0)
ImportError: No module named sklearn.cross_validation
It must relate to the renaming and deprecation of
cross_validationsub-module tomodel_selection. Try substitutingcross_validationtomodel_selectionFrom Stack Overflow: asked by arthurckl, answered by Dima Lituiev (CC BY-SA 4.0)
Save classifier to disk in scikit-learn
Classifiers are just objects that can be pickled and dumped like any other. To continue your example:
import cPickle # save the classifier with open('my_dumped_classifier.pkl', 'wb') as fid: cPickle.dump(gnb, fid) # load it again with open('my_dumped_classifier.pkl', 'rb') as fid: gnb_loaded = cPickle.load(fid)From Stack Overflow: asked by garak, answered by mwv (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA13 questions