text
stringlengths 81
47k
| source
stringlengths 59
147
|
|---|---|
Question: <p>I need some suggestions to improve my model accuracy.</p>
<p>The training data shape is : (166573, 14)</p>
<p><a href="https://i.sstatic.net/fFpjX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fFpjX.png" alt="train data"></a></p>
<p>It has all int and float columns. I have dropped <em>claims_daysaway</em> column as most of values are NaN and replaced Nan value with mean for tier column.</p>
<pre><code>X_train = train.drop(['outcome','testindex','claims_daysaway'], axis=1)
y_train = train['outcome']
</code></pre>
<p><a href="https://i.sstatic.net/h3Jx4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/h3Jx4.png" alt="enter image description here"></a></p>
<p>As the values were on different scale, I have used StandScaler() to standardize values.</p>
<p><a href="https://i.sstatic.net/iVsg0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iVsg0.png" alt="enter image description here"></a></p>
<p>This dataset is highly imbalanced.</p>
<blockquote>
<p>train['outcome'].value_counts() </p>
</blockquote>
<pre><code>0 159730
1 6843
</code></pre>
<p>I tried SMOTE for oversampling.</p>
<pre><code>from imblearn.over_sampling import SMOTE
smt = SMOTE()
X_train, y_train = smt.fit_sample(X_train, y_train)
pd.value_counts(pd.Series(y_train))
1 159730
0 159730
</code></pre>
<p>Lastly, I fit model using <strong>XGBClassifier</strong> but when tried this model on testdata and submitted it, it gives only 60% roc_auc_score.</p>
<p>Please suggest how to handle imbalanced dataset better.</p>
Answer: <p>I'm not very sure what you mean by "<em>60% accuracy using AUC</em>". Accuracy and AUC are two different metrics... I'm going to answer as if you're referring to classification accuracy, since that's in your title and the first sentence of your post.</p>
<p>First of all, <strong>don't use accuracy to evaluate performance on imbalanced data</strong>!</p>
<p>Your dataset has an imbalance ratio of 6843/159730 which is around 1/23. This means that if you make a dummy classifier that just predicts the majority class you'd get an accuracy of 96%. There are better options for imbalanced data such as the <a href="https://en.wikipedia.org/wiki/F1_score" rel="noreferrer">f1 score</a> or any macro-averaged metric (you can read <a href="https://datascience.stackexchange.com/a/36302/34269">this post</a> more information).</p>
<p>Secondly, I'm not sure what you're doing it but, just in any case, you <strong>shouldn't evaluate on the oversampled dataset</strong>. </p>
<p>As for <strong>ideas</strong> for improving performance, I don't have many because you are doing most things right. <strong>Tree-based algorithms</strong> (e.g. XGBoost) are good for dealing with imbalanced data. You are already <strong>oversampling</strong> the data, which helps a lot. Some other ideas are:</p>
<ul>
<li>Try different oversamplers, undersamplers or perhaps a combination of over and under-sampling techniques.</li>
<li>Search to optimize the hyperparameters of your XGBoost. I can't tell by the information you gave, but maybe you're overfitting. </li>
<li>Try different algorithms (catboost, lightgbm, etc.), or maybe ensembles of those models (stacked models, etc.).</li>
</ul>
|
https://datascience.stackexchange.com/questions/49668/improving-accuracy-on-highly-imbalanced-dataset
|
Question: <p>I am currently dealing with a classification problem for a massively imbalanced dataset. More specifically, it is a fraud detection dataset with around 290k rows of data, with distribution of 99.8% for class 0 (non-frauds) and 0.17% for class 1 (frauds).</p>
<p>I have been using XGBoost, Random Forest and LightBGM as my predictive models. I have also tried running the models differently by tuning class weights and resampling the dataset to bring it on a balanced scale. Moreover, I used f1-score, ROC-AUC score and a Precision-Recall curve as my main metrics, as it seems that other metrics are not representative of the result on an imbalanced dataset.</p>
<p>However, I seem to still be overfitting massively on my training data. In all scenarios, the f1-score, ROC-AUC score and the AP from Precision-Recall Curve of my training set are either 1.0 or 0.999, whereas those of the testing set are roughly around 0.85. <br></p>
<p>I wanted to ask whether this is a normal occurrence for an imbalanced dataset, and if not, is there any other method for me to fix it.</p>
<p>I would appreciate any response, and thank you all very much!</p>
Answer: <p>I am also facing the same issue in the Intrusion Detection System. I found the following suggestions that can be useful:</p>
<ul>
<li>Reduce the number of datapoints with 0s to reduce the imbalance in dataset - Downsampling.</li>
<li>Obtain more data for the minor class (might not be possible, but is one solution)</li>
<li>Using Confusion matrix to analyze the model performance as well as the metrics you are already using</li>
<li>Using either Specificity or Recall as a metric to train the model</li>
</ul>
|
https://datascience.stackexchange.com/questions/120685/interpretation-of-evaluation-metrics-for-an-imbalanced-dataset
|
Question: <p>I am dealing with imbalanced dataset and I try to make a predictive model using MLP classifier. Unfortunately the algorithm classifies all the observations from test set to class "1" and hence the f1 score and recall values in classification report are 0. Does anyone know how to deal with it?</p>
<pre><code>model= MLPClassifier(solver='lbfgs', activation='tanh')
model.fit(X_train, y_train)
score=accuracy_score(y_test, model.predict(X_test), )
fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:,1])
roc=roc_auc_score(y_test, model.predict_proba(X_test)[:,1])
cr=classification_report(y_test, model.predict(X_test))
</code></pre>
Answer: <p>You can try using <strong>data re-sampling</strong> techniques. They can be divided in four categories: undersampling the majority class, oversampling the minority class, combining over and under sampling, and creating an ensemble of balanced datasets.</p>
<p>The above methods and more are implemented in the <a href="https://github.com/scikit-learn-contrib/imbalanced-learn" rel="nofollow noreferrer">imbalanced-learn</a> library in Python that interfaces with scikit-learn. See <a href="https://github.com/vsmolyakov/experiments_with_python/blob/master/chp01/imbalanced_data.ipynb" rel="nofollow noreferrer">ipython notebook</a> for an example.</p>
|
https://datascience.stackexchange.com/questions/19801/imbalanced-dataset-in-mlp-classifier-in-python
|
Question: <p>I have a classifier with a heavily imbalanced dataset (1000 of each negative label for each positive.)</p>
<p>I'm running a GradientBoostingClassifier with moderate success (AUC .75) but the curve has this strange look:</p>
<p><a href="https://i.sstatic.net/8E0y9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8E0y9.png" alt="enter image description here"></a></p>
<p>Any good ideas on what would cause the curve to have this behaviour?</p>
Answer: <p>Davis and Goadrich have explained the relationship between ROC and PR Curves in their <a href="http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_DavisG06.pdf" rel="nofollow noreferrer">paper</a>. It is always recommended to use PR curve over the ROC curve in the presence of highly imbalanced data. </p>
<p>Back to the behavior of your ROC curve, It seems that you don't have more threshold points! I would also agree with Dan and do K-fold CV. </p>
<blockquote>
<p>Davis, J. and Goadrich, M., 2006, June. The relationship between
Precision-Recall and ROC curves. In Proceedings of the 23rd
international conference on Machine learning (pp. 233-240). ACM.</p>
</blockquote>
|
https://datascience.stackexchange.com/questions/24315/roc-curve-shows-strange-results-for-imbalanced-dataset
|
Question: <p>The xgboost classifier states the use of parameter <code>scale_pos_weight</code> for 2-class problems.</p>
<p>I have a highly imbalanced dataset with 3 classes. Classes '1' and '-1' are very rare (~1% of dataset) and class '0' is very common. </p>
<p>How do I set this <code>scale_pos_weight</code> parameter in the xgboost classifier correctly for my classification problem?</p>
Answer: <p>For my multiclass classification problem with similar unbalanced data I used the output from sklearn <code>compute_class_weight</code> function:</p>
<p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.compute_class_weight.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.compute_class_weight.html</a></p>
<pre><code>sklearn.utils.class_weight.compute_class_weight(class_weight, classes, y)
</code></pre>
|
https://datascience.stackexchange.com/questions/43376/imbalanced-dataset-with-3-classes-xgboost-scale-pos-weight-parameter
|
Question: <p>I have a dataset where around 20% of the data is the positive class and 80% of the data is the negative class. When I undersample and train my classifier on a balanced dataset and test on a balanced dataset, the results are pretty ok. However, if I train on the balanced dataset and test on an imbalanced dataset that replicates the real world (80-20 split) the metrics are not great. Should I train the model on the original imbalanced dataset if I want it to perform well on real world test data that is also imbalanced.</p>
Answer: <blockquote>
<p>When I undersample and train my classifier on a balanced dataset and test on a balanced dataset, the results are pretty ok</p>
</blockquote>
<p>It's not surprising that the results are good since the job is easier in this case. It's actually a mistake to test on the artificially balanced dataset, since it's not a fair evaluation of how the system will perform with real data.</p>
<blockquote>
<p>Should I train the model on the original imbalanced dataset if I want it to perform well on real world test data that is also imbalanced.</p>
</blockquote>
<p>Both training on the original dataset or the balanced dataset are valid methods, choosing between the two options is a matter of design and performance. It's often a good idea to try both and then pick the one which performs better than the other on the real imbalanced dataset.</p>
|
https://datascience.stackexchange.com/questions/66839/if-a-dataset-is-imbalanced-in-real-life-should-i-train-on-my-machine-learning-m
|
Question: <p>I like to understand what is the accuracy of an imbalanced dataset.</p>
<p>Let's suppose we have a medical dataset and we want to predict the disease among the patients. Say, in an existing dataset 95% of patients do not have a disease, and 5% patients have disease. So clearly, it is an imbalanced dataset. Now, assume our model predicts that all 100 out of 100 patients have no disease.</p>
<p>Accuracy means = (TP+TN)/(TP+TN+FP+FN)</p>
<p>If the model predicts 100 patients do not have a disease and we are predicting disease among the patient then True positive refers to the disease among the patient and True negative refers to no disease among the patient.</p>
<p>In that case accuracy should be (0+100)/(0+100+0+0) = 1.</p>
<p>We are going to predict how many patients have a disease so if we get accuracy 1, does that mean 100% of patients have the disease?</p>
<p>I am taking the example from <a href="https://www.analyticsvidhya.com/blog/2021/06/5-techniques-to-handle-imbalanced-data-for-a-classification-problem/#:%7E:text=Imbalanced%20data%20refers%20to%20those,very%20low%20number%20of%20observations." rel="nofollow noreferrer">5 Techniques to Handle Imbalanced Data For a Classification Problem</a> . I am not sure at the time of accuracy calculation why they calculate it as (0+95)/(0+95+0+5) = 0.95, if they have already described that their model predicts <code>all 100 out of 100 patients have no disease.</code></p>
<p>I hope I clarified my question. Thank you.</p>
Answer: <p>Accuracy is the number of correct predictions out of the number of possible predictions. In many regards, it is like an exam score: you had an opportunity to get <span class="math-container">$100\%$</span> of the points and got <span class="math-container">$97\%$</span> or <span class="math-container">$79\%$</span> or whatever. The class ratio is not a factor.</p>
<p>In your example, you had <span class="math-container">$95$</span> negative patients and <span class="math-container">$5$</span> positive. You predicted <span class="math-container">$100$</span> negative patients, meaning that you got <span class="math-container">$95$</span> correct and <span class="math-container">$5$</span> incorrect for an accuracy of <span class="math-container">$95\%$</span>.</p>
<p>Note that accuracy is a surprisingly problematic measure of performance, and this is true <a href="https://stats.stackexchange.com/a/312787/247274">even when the classes are naturally balanced</a>.</p>
<p>With imbalance, however, accuracy has the potential to mislead in a way that is not present in many other measures of performance, and your example is a good demonstration of that. All your model does is predict the majority class; it does nothing clever. However, your model achieves an accuracy of <span class="math-container">$95\%$</span>, which sounds like a high <span class="math-container">$\text{A}$</span> in school that indicates strong performance.</p>
|
https://datascience.stackexchange.com/questions/114297/how-to-calculate-accuracy-of-an-imbalanced-dataset
|
Question: <p>I plan to use many methods to solve the imbalanced dataset problem on the training set. But I couldn't find any paper that describes how they dealt with the test dataset? I assume that they just tested on the original dataset without any adjustments? Will I need to adjust the threshold on the test set with original imbalanced ratio?</p>
<hr />
<p>update. Thanks for everyone's response!</p>
<p>I've found a paper that discusses how we should adjust the posterior probability and threshold.
<a href="http://www.ulb.ac.be//di/map/adalpozz/pdf/SSCI_calib_final_noCC.pdf" rel="nofollow noreferrer">Calibrating Probability with Undersampling
for Unbalanced Classification</a></p>
<p>However, I also believe that in practice we can just fit test set directly.</p>
Answer: <p>You should use the testing set without any change, as answered by others. But it is very important to understand the difference between average accuracy and overall accuracy.
In overall accuracy you find ( number of samples predicted correctly/ total number of samples) in average accuracy, you find the overall accuracy per class and then you find the average of these overall accuracies.
When you know that you are working with imbalanced database, where all classes are important, you should use the average accuracy </p>
<p>To understand what this means: imagine you have two classes, class A and class B , and the ratio is 90 to 10 .
If you are sampling randomly for the training and testing, then the ratio is still 90:10 in the testing set. If your model is very biased , that predicts all the samples to be class A , then:
Overall accuracy = 90%
Average accuracy = 50 %
( 100% for class A + 0% for class B) / 2 </p>
<p>The overall accuracy is really high but it does not reflect the actual quality of the model. The average accuracy gives you a better indication of the quality </p>
|
https://datascience.stackexchange.com/questions/17873/imbalanced-dataset-how-to-deal-with-test-data
|
Question: <p>I was wondering what is the right way to proceed when you are dealing with an imbalanced dataset and you want to use a calibrator. When I work with a single model and imbalanced datasets I usually pass "sample_weights" to the model, but I don't know if "sample_weights" should be passed to the calibrator as well.</p>
Answer:
|
https://datascience.stackexchange.com/questions/108427/should-i-use-sample-weights-on-a-calibrator-if-i-already-used-them-while-train
|
Question: <p>I have a <strong>text datase</strong>t where I need to train a classifier to classify the titles into categories. The dataset shape is more than 575000. There are 256 target classes here. The problem is the dataset is highly imbalanced. For target <strong>X1 it has 171793 records, X2 has 101575,........Xn-1 has 2, Xn has 2 records</strong>. Consider the target value counts are in decreasing order. </p>
<p>To handle with the imbalanced dataset, <strong>oversampling and undersampling</strong> works for multiclass say 3 classes. But in my case, there are 256 classes. How do I sample my dataset in this situation? How do I sample the dataset in a way so my model is stable for all the targets? </p>
<p>Do I have to remove the classes which have value counts 2 - 100 from this dataset? and apply undersampling/oversampling. Is there any approach to handle these type of situation? </p>
Answer: <p>The situation you describe is a <a href="https://data4thought.com/fewshot_learning_nlp.html#fewshot_learning_nlp" rel="nofollow noreferrer">few-shot learning problem</a>: you have a lot of classes and only a few examples for some of them.</p>
<p>Similarity metric learning with siamese neural networks is well suited for this task. The idea is to learn a general similarity metric between examples, then classify new examples as belonging to the class of the "closest" sample from the training set. It seems a bit complex but it's probably the best way to learn "across" classes. </p>
<p>The link I've shared above is applied to an NLP problem so should be able to reuse it fairly easily.</p>
|
https://datascience.stackexchange.com/questions/60936/highly-imbalanced-dataset-fro-classes-more-than-200
|
Question: <p>Let's suppose that my dataset in a classification problem looks like that:</p>
<ol>
<li>class A: 50000 observations</li>
<li>class B: 2000 observations</li>
<li>class C: 800 observations</li>
<li>class D: 200 observations</li>
</ol>
<p>These are some ways which I considered to deal with this imbalanced dataset:</p>
<ol>
<li><p>I reject straight away oversampling because it usually makes the model overfit (in the minority classes) by a lot.</p></li>
<li><p>Secondly, if I run the classifier with the data like that then it will be overclassifying documents in class A so I reject this method too.</p></li>
<li><p>Another approach is to do undersampling and reduce class A to let's say 4000 documents (where I tested it and it gives the best results so far).</p></li>
<li><p>However, in this way I am losing quite a lot of information. So I am wondering if building multiple classifiers with 4000 documents each for class A (different at each time) is a better solution (although I think that this approach resembles quite a lot the oversampling approach which I rejected).</p></li>
</ol>
<p>What do you think of method (4) comparing to method (3)?</p>
Answer: <p>Maybe your (3) can be complemented to an oversampling of the other classes. I don't think every oversampling generates overfitting. I agree with you, it will make you lose information. But the only way to know if it's that bad is by checking it.</p>
<p>Regarding (4), I don't see how you'll manage the predictions of these multiple classifiers. You could test binary classifiers for each class, like classifier1 for A/not-A, classifier2 for B/not-B. In this case, undersampling could be applied.</p>
<p>However, all these advices are just speculation. You must test on your data, and see the results with more evaluation tools, such as learning curves and feature importance analysis. </p>
|
https://datascience.stackexchange.com/questions/61814/imbalanced-dataset-undersampling-multiple-classifiers
|
Question: <p>I have a dataset containing thousands of text posts. I am building a binary classifier that will classify posts as <strong>safe (0)</strong> or <strong>risky (1)</strong>. I randomly picked some of them and manually labeled. Label 1 is minority.</p>
<p>Imbalanced data results in skewed performance. To overcome this, I undersample to obtain a 50%/50% distribution for both train and test set.</p>
<ul>
<li>If I use stratified strategy (in scikit-learn) for ZeroR, it acts like <strong>random guesser</strong>. <strong>Is this a good baseline</strong>?</li>
<li><p>If I use <strong>"guess 1"</strong> all the time, then its <strong>recall is 100%</strong> all the time. However <strong>recall is the most important metric</strong> for me. So other algorithms' predictions look unsuccessful. Should I ignore recall when using ZeroR and only compare accuracy?</p></li>
<li><p>I also would like to apply 10-fold cross validation, should I apply undersampling before splitting as well?</p></li>
<li>Or instead should I go with F1-Score without undersampling? This time ZeroR has high F1 score due to 100% Recall.</li>
</ul>
Answer: <p>You should only undersample the data that is used for training. Test data should represent the true distribution.</p>
<p>Then you have at least two possible baselines. One is ZeroR (your second point), which always predicts the majority class. Given a true distribution of (0) 10% and (1) 90%, this would give you a recall of 100% for (1) and 0% for (0) and 90% accuracy. </p>
<p>If rows represent the true labels and the columns the predictions, the confusion matrix looks something like this:</p>
<p>$\begin{bmatrix}90 & 0\\10 & 0\end{bmatrix}$</p>
<p>The other would be to flip a coin with probability 90% for class (1) (your first point but without undersampling), which gives you a recall of 90% for (1) and 10% for (0), and 82% accuracy, which is a little more balanced:</p>
<p>$\begin{bmatrix}81 & 9\\9 & 1\end{bmatrix}$</p>
<p>If your classes are strongly imbalanced then recall and accuracy have the same problems as you noted above. F1 might be a better choice, but the best metric depends on your application.</p>
|
https://datascience.stackexchange.com/questions/24787/zeror-as-baseline-for-balanced-imbalanced-datasets
|
Question: <p>I have a multi-class prediction problem<br/>
but the 300classes is imbalanced <br/>
should I make it balance all 300 class will predict the better result? <br/>
is there an easier method to do this job?<br/>
if I'm using the random-forest imbalance dataset is matter?</p>
Answer: <p>Nothing better if you could get more data and make classes (at least close to) balanced!</p>
<p>Choice of algorithm (I believe you using only RFC) entirely depends upon problem statement and as we all know, there is no free lunch in statistics, so you might've to try other algorithms (or just create a pipeline trying few more) as well.</p>
<p>Try over/under sampling and penalize your model by applying some custom matrix for miss classification, if required. Another point to keep note of is performance metric (avoid Accuracy paradox). Apart from deeper dive with <code>F1</code>, <code>Recall</code> & <code>Precision</code>; also try to look into <code>[Kappa]</code><a href="https://en.wikipedia.org/wiki/Cohen%27s_kappa" rel="nofollow noreferrer">1</a> or <code>[ROC curves]</code><a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic" rel="nofollow noreferrer">2</a>.</p>
<p>Based on the limited information (better idea would be to add a graph showing class imbalance) you've provided, this is the best I recommend. Hope it helps!</p>
|
https://datascience.stackexchange.com/questions/67312/imbalanced-target-datasetmulti-class
|
Question: <p>Im trying to use gridsearch to find the best parameter for my model. Knowing that I have to implement nearmiss undersampling method while doing cross validation, should I fit my gridsearch on my undersampled dataset (no matter which under sampling techniques) or on my entire training data (whole dataset) before using cross validation?</p>
Answer: <p><strong>Do grid search on the same Level of "imbalancedeness" that you plan/are able to do your Training and Evaluation on.</strong></p>
<p>So that means that if you saw that imbalanced data set does not skew your model predictions or results in other unwanted Outcomes, done use the maximal dataset possible. But on the other Hand if your model is strongly overfitting because of imbalanced dataset then optimisation with grid search will make him overfit more in that direction.</p>
|
https://datascience.stackexchange.com/questions/89428/gridsearch-on-imbalanced-datasets
|
Question: <p>I have used an "adabag"(boosting + bagging) model on an imbalanced dataset (6% positive), I have tried to maximized the sensitivity while keeping the accuracy above 70% and the best results I got were: </p>
<ul>
<li>ROC= 0.711 </li>
<li>SENS=0.94 </li>
<li>SPEC=0.21</li>
</ul>
<p>The results aren't Inhofe, especially the bad specificity.
Any suggestion on how to improve the result? Can the optimization be improved, or would the addition of a penalty term help? </p>
<p>This is the code:</p>
<pre><code>ctrl <- trainControl(method = "cv",
number = 5,
repeats = 2,
p = 0.80,
search = "grid",
initialWindow = NULL,
horizon = 1,
fixedWindow = TRUE,
skip = 0,
verboseIter = FALSE,
returnData = TRUE,
returnResamp = "final",
savePredictions = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary,
preProcOptions = list(thresh = 0.80, ICAcomp = 3, k = 7, freqCut = 90/10,uniqueCut = 10, cutoff = 0.2),
sampling = "smote",
selectionFunction = "best",
index = NULL,
indexOut = NULL,
indexFinal = NULL,
timingSamps = 0,
predictionBounds = rep(FALSE, 2),
seeds = NA,
adaptive = list(min = 5,alpha = 0.05, method = "gls", complete = TRUE),
trim = FALSE,
allowParallel = TRUE)
grid <- expand.grid(maxdepth = 25, mfinal = 4000)
classifier <- train(x = training_set[,-1],y = training_set[,1], method = 'AdaBag',trControl = ctrl,metric = "ROC",tuneGrid = grid)
prediction <- predict(classifier, newdata= test_set,'prob')
</code></pre>
<p>plot from classifierplots package:</p>
<p><a href="https://i.sstatic.net/9K8CX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9K8CX.png" alt="enter image description here"></a></p>
<p>I tried xgboost as well.</p>
<p>Here is the code:</p>
<pre><code>gbmGrid <- expand.grid(nrounds = 50, eta = 0.3,max_depth = 3,gamma = 0,colsample_bytree=0.6,min_child_weight=1,subsample=0.75)
ctrl <- trainControl(method = "cv",
number = 10,
repeats = 2,
p = 0.80,
search = "grid",
initialWindow = NULL,
horizon = 1,
fixedWindow = TRUE,
skip = 0,
verboseIter = FALSE,
returnData = TRUE,
returnResamp = "final",
savePredictions = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary,
sampling = "smote",
selectionFunction = "best",
index = NULL,
indexOut = NULL,
indexFinal = NULL,
timingSamps = 0,
predictionBounds = rep(FALSE, 2),
seeds = NA,
adaptive = list(min = 5,alpha = 0.05, method = "gls", complete = TRUE),
trim = FALSE,
allowParallel = TRUE)
classifier <- train(x = training_set[,-1],y = training_set[,1], method = 'xgbTree',metric = "ROC",trControl = ctrl,tuneGrid = gbmGrid)
prediction <- predict(classifier, newdata= test_set[,-1],'prob')
</code></pre>
<p>plot from classifierplots package:</p>
<p><a href="https://i.sstatic.net/KhSlQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KhSlQ.png" alt="enter image description here"></a></p>
<p><strong>Update:</strong></p>
<p>I tried asymmetric adaboost, this is the code:</p>
<pre><code>model_weights <- ifelse(training_set$readmmited == "yes",
(1/table(training_set$readmmited)[1]) * 0.4,
(1/table(training_set$readmmited)[2]) * 0.6)
ctrl <- trainControl(method = "repeatedcv",
number = 5,
repeats = 2,
search = "grid",
returnData = TRUE,
returnResamp = "final",
savePredictions = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary,
selectionFunction = "best",
allowParallel = TRUE)
classifier <- train(x = training_set[,-1],y = training_set[,1], method = 'ada',trControl = ctrl,metric = "ROC",weights = model_weights)
</code></pre>
<p>but the specificity is zero, what am I doing wrong?</p>
Answer: <p>You should try compensating for the imbalanced data and then can you try a lot of different classifiers. Either balance it out, use SMOTE to interpolate (this always struck me as too magical), or assign weights.</p>
<p>Here's a nice article walking through it with caret, which is what it appears you're using:</p>
<p><a href="http://dpmartin42.github.io/blogposts/r/imbalanced-classes-part-1" rel="nofollow noreferrer">http://dpmartin42.github.io/blogposts/r/imbalanced-classes-part-1</a></p>
|
https://datascience.stackexchange.com/questions/18295/improving-classifier-performances-in-r-for-imbalanced-dataset
|
Question: <p>I have an imbalanced dataset (2:1 ratio) with about 60 patients and 80 features.</p>
<p>I performed Recursive Feature Elimination (RFE) and stratified cross validation to reduce the features to 15 and I get an AUC of 0.9 with Logistic regression and/or SVM. I don't fully trust the AUC I got because I think it will not generalize correctly because of such a small positive class.
So, I was thinking on oversampling (K-means + PCA) the minority class and re-run the RFE approach, would this help?
Thanks.</p>
<p>My question is more or less the same as this one: <a href="https://datascience.stackexchange.com/questions/28227/why-will-the-accuracy-of-a-highly-unbalanced-dataset-reduce-after-oversampling">Why will the accuracy of a highly unbalanced dataset reduce after oversampling?</a>
but I do use AUC.</p>
Answer: <p>The bigger issue might be the small <code>n</code>. With 60 samples and 2:1 ratio, you only have 20 samples in the minority class. Generalization, no matter what machine learning technique is used, will be limited with just 20 samples.</p>
|
https://datascience.stackexchange.com/questions/66779/will-oversampling-help-with-generalization-small-imbalanced-dataset
|
Question: <p>Let's say that I have a 2-class classification problem where classes <code>A & B</code> have <code>10*N</code> and <code>N</code> observations respectively.</p>
<p>I am pretty sure that the answer to my question depends on the specific classification problem and on the features of my dataset etc.. Still there are general analysis that can be done on my question.?</p>
<p>Something that I could clarify is that I am interested in having high recall in both classes ("macro-average recall"); not primarily in having the highest possible recall in the minority class as in imbalanced dataset classification problems such as spam detection, financial fraud detection or disease detection. </p>
<p>So for this, generally speaking, is it better to train my model on:</p>
<p>1) A: 10*N observations, B: N observations</p>
<p>2) A: 5*N observations, B: N observations</p>
<p>3) A: N observations, B: N observations</p>
<p>I am having an impression, that assuming we start with a balanced dataset then the more data you add to one class then the better the <code>macro-average recall</code> because of the new information added but after one point the dataset becomes so imbalanced that the performance of the model on the minority class probably deteriorates and hence the <code>macro-average recall</code> falls.</p>
<p>Am I right on this?</p>
Answer: <p>It's an interesting problem, but I think the answer might be disappointing:</p>
<p>Usually problems about maximizing recall are considered in the context of a trade-off with precision, i.e. the goal is to sacrifice some precision by predicting more positives, whether true (TP) or false (FP). Usually in a binary problem this is possible because we focus on one class of importance and consider the other as irrelevant, so its performance doesn't matter.</p>
<p>Here we have a binary problem where we want to maximize recall <em>for both classes</em>, so we cannot sacrifice one for the sake of the other: any gain in recall for a class is likely to cause a loss in recall for the other class, since predicting more instances as positive for class A would mean more negative instances for class B, and conversely. If we were talking micro-recall we could still use the higher importance in proportion of class A, but with macro-recall we can't. Note that this is a typical case where accuracy could be used, since it would give the same weight to both classes and would be a much simpler metric.</p>
<p>So the only way to improve macro-recall is to increase true positives. Let's look at the options:</p>
<blockquote>
<p>1) A: 10*N observations, B: N observations</p>
</blockquote>
<p>Pro: performance for class A is maximized. Cons: class B proportionally disadvantaged, so possible loss in its performance.</p>
<blockquote>
<p>2) A: 5*N observations, B: N observations</p>
</blockquote>
<p>Cons: class A a bit less advantaged; pro: class B a bit less disadvantaged.</p>
<blockquote>
<p>3) A: N observations, B: N observations</p>
</blockquote>
<p>Pro: maximum performance for class B; cons: class A underperforms.</p>
<p>Actually the best option is probably to use all of N*10 instances for A and repeat 10 times the N instances for B, so that:</p>
<ul>
<li>the learning method can benefit from all the available training data for A</li>
<li>class B is not proportionally disadvantaged.</li>
</ul>
<p>But my guess is that it's unlikely to make a very big difference anyway. When it's a matter of increasing true positives, it's usually the features and the ML method which can have an impact.</p>
|
https://datascience.stackexchange.com/questions/64706/training-model-on-a-balanced-vs-imbalanced-dataset
|
Question: <p>There's an imbalanced dataset in a Kaggle competition I'm trying. The target variable of the dataset is binary and it is biased towards 0.
0 - 70%
1 - 30%
I tried several machine learning algorithms like Logistic Regression, Random Forest, Decision Trees etc. But all of them give an accuracy around 70%. It seems that the models always tend to predict 0.
So I tried several methods to get an unbiased dataset like the following.</p>
<ol>
<li>Up sampling the dataset using SMOTE and other techniques.</li>
<li>Under sampling the dataset</li>
<li>Changing the weight of the model.</li>
</ol>
<p>But all of these steps reduced the accuracy instead of increasing. Area under the curve and precision was improved but unfortunately I have to increase the accuracy somehow to win the competition.</p>
<p>So I would really appreciate it if you could tell me about the techniques to improve the accuracy in an imbalanced dataset.</p>
Answer: <p>Following your comment, I'll detail here (too long for comments basically)</p>
<p>Acuracy may not be a good way to measure your model's performance. Imagine a problem with 99 '0' and 1 '1'. A model always gessing '0' will have 99% accuracy, and is useless, since you want to detect the '1'. A model giving you 10 '1' including the real one is way better, and have a way lower accuracy.</p>
<p>You then have to define your problem correctly, and change metric according to it. For example, one of the useful metric in those cases can be AUC, since it's not affected by unbalanced datasets.</p>
<p>So one of the methods you could apply, is trying to maximize AUC, and when you found the good model, manually select your 30% best-scored features in your test. If you find half the true '1' on your selection, this can already be a really good result (according to the problem difficulty) while accuracy would be way worse.</p>
<p>You really have to adapt the metric you try to maximise to your problem : since here, there are more possibilities of being '0' than '1', accuracy is pretty good with a classifier always guessing '0', and tuning your model following accuracy could turn you to such a classifier.</p>
|
https://datascience.stackexchange.com/questions/98213/how-to-increase-the-accuracy-of-an-imbalanced-dataset-not-precision
|
Question: <p><a href="https://i.sstatic.net/5yOLt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5yOLt.png" alt="class distribution looks like this" /></a><a href="https://i.sstatic.net/4VseP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4VseP.png" alt="this is how the dataset looks like" /></a>I have a dataset with size ~ 500k entries. There are 2 columns, 'product description' and 'level 1'. I am developing my model such that it learns from a training set of 350k and based on the product description for test data, it gives the values in 'Level 1'. A simple linear classifier gives an accuracy of 85% which is too low, I am aiming for 97% atleast. I think this might be because the dataset is imbalanced, the level 1 values in the training data are imbalanced. How do I resolve this? Can I make the upsampling minority and downsampling majority work here?</p>
Answer:
|
https://datascience.stackexchange.com/questions/78400/text-classification-of-an-imbalanced-dataset
|
Question: <p>Imagine I have a dataset with positive and negative sentences, and I need to train a transformer (Like BERT) to do the binary classification. The problem is that there are 100 negative sentences and 2000 positive sentences. There are libraries for NLP data augmentation like this one: <a href="https://github.com/makcedward/nlpaug" rel="nofollow noreferrer">https://github.com/makcedward/nlpaug</a></p>
<p>But how many new instances should I add to the minor class? Since my dataset is highly imbalanced, should I try to add 1900 instances to the minor class so that both classes have an equal population?</p>
<p>In order to make the imbalance ratio 1 in a highly imbalanced dataset such as mine, I have to use each sentence to generate 19 new sentences. If several of them are too alike, my model will end up overfitted.</p>
Answer: <p>There is nothing wrong with an imbalanced training dataset. It's possible that no changes are required.</p>
<p>When your training set is highly imbalanced like this, models in early training stages will predict everything to be the most prevalent class (positive in this case). After a longer training period, usually the model moves out of this local minima and starts making actual meaningful predictions. If it does, this is the ideal scenario because the model is using knowledge both of the text in the individual samples, but also of the class prevalences. Sometimes though, the model never escapes the local minima, and only then should you try to augment your training set.</p>
|
https://datascience.stackexchange.com/questions/102181/how-much-data-augmentation-is-required-on-an-imbalanced-dataset
|
Question: <p>I trained a binary classifier for an imbalanced dataset. I did two experiments:</p>
<ol>
<li><strong>lightgbm classifier, boosting_type='gbdt', objective='cross_entropy', SMOTE upsample</strong></li>
</ol>
<p>After training the lgbm model, I made predictions on validation dataset. I plotted the probability distribution as follow:</p>
<p><a href="https://i.sstatic.net/lrUGh.png" rel="nofollow noreferrer">lightgbm output probability distribution</a></p>
<p>Plot code:</p>
<pre><code>fig = plt.figure()
tmp = pd.Series(pred_y)
ax = tmp.plot.kde()
fig.savefig('xx.png')
</code></pre>
<ol start="2">
<li><strong>Standard Scaler, sklearn logistic regression, class_weight='balanced'</strong></li>
</ol>
<p>The output probability distribution of validation dataset is as follow:</p>
<p><a href="https://i.sstatic.net/f1rb2.png" rel="nofollow noreferrer">logistic output probability distribution</a></p>
<p>Why does the lightgbm output probability distribution have some output values near 0.5 and 0.75?
Unlike a logistic model, just output probability either near 0, or near 1. For that lightgbm model is a decision forest, and add many outputs from many trees to produce the final probability?
Or is it because the dataset is imbalanced?</p>
<p><a href="https://i.sstatic.net/9Pk51.png" rel="nofollow noreferrer">differences</a></p>
Answer:
|
https://datascience.stackexchange.com/questions/102129/binary-classification-with-imbalanced-dataset-about-lightgbm-output-probability
|
Question: <p>I have a data set collected from Facebook consists of 10 class, each class have 2500 posts, but when count number of unique words in each class, they has different count as shown in the figure <a href="https://i.sstatic.net/eUIMX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eUIMX.png" alt="word count in each class"></a></p>
<p>Is this an imbalanced problem due to word count , or balanced according number of posts. and what is the best solution if it imbalanced?</p>
<p><strong>update</strong>
My python code:</p>
<pre><code>data = pd.read_csv('E:\cluster data\One_File_nonnormalizenew2norm.txt', sep="*")
data.columns = ["text", "class1"]
data.dropna(inplace=True)
data['class1'] = data.class1.astype('category').cat.codes
text = data['text']
y = (data['class1'])
sentences_train, sentences_test, y_train, y_test = train_test_split(text, y, test_size=0.25, random_state=1000)
from sklearn.feature_extraction.text import CountVectorizer
num_class = len(np.unique(data.class1.values))
vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)
model = Sequential()
max_words=5000
model.add(Dense(512, input_shape=(60874,)))
model.add(Dense(20,activation='softmax'))####
model.summary()
model.compile(loss='sparse_categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(X_train, y_train,batch_size=150,epochs=10,verbose=2,validation_data=(X_test,y_test),shuffle=True)
predicted = model.predict(X_test)
predicted = np.argmax(predicted, axis=1)
accuracy_score(y_test, predicted)
predicted = model.predict(X_test)
predicted = np.argmax(predicted, axis=1)
accuracy_score(y_test, predicted)
0.9592031872509961
</code></pre>
Answer: <p>Thank you for your message Ahmed. There are things to point out:</p>
<ol>
<li><em>Is this an imbalanced problem?</em> Which problem? <strong>THIS</strong> is not a problem. This is data.</li>
<li>What analysis is going to be done? In some cases you need posts and in some you need these keywords. </li>
<li>What method is going to be done for that analysis? Some methods get keywords as input and some get posts.</li>
</ol>
<p>But about the numbers themselves; Not necessarily. The smallest class has 20% of the largest population and moreover, the scale is pretty high (20000 samples). So it is not necessarily an imbalanced class distribution. Again, see what you want to do with this data. That determines the answer much more accurate.</p>
<p>Hope it helped. If you write about the task you want to do I can post the solution here.</p>
<p>Cheers,</p>
<h2>UPDATE</h2>
<p>Well, then the problem is pretty straight-forward. These unique words are probably not much meaningful here. I certainly recommend that you try BoW models first (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow noreferrer">TF-IDF</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer" rel="nofollow noreferrer">classic BoW</a>) for modeling your corpus. Then tune the hyperparameters of models and using a simple Multinomial Naive Bayes you will get an acceptable result. </p>
<p>Data is not counted that imbalanced. I had a problem in which some classes had 3000-4000 samples and some only 20! That is certainly called imbalanced but here you still have enough data to represent your minority class and also you will use Precision-Recall for evaluation instead of Accuracy so you will be fine. I strongly recommend you to have a look at <a href="https://github.com/kasramsh/Feature-Engineering/blob/master/Text/NSF%20Awards.ipynb" rel="nofollow noreferrer">this</a> for Python implementation and also seeing some imbalanced data in practice.</p>
<p>The DL thing is answered in the comment. </p>
|
https://datascience.stackexchange.com/questions/45163/imbalanced-dataset-in-text-classififaction
|
Question: <p>I am trying to make some semantic segmentation. I have 7 imbalanced classes in my case.
I found several methods for handling Class Imbalance in a dataset is to perform Undersampling for the Majority Classes or Oversampling for the minority classes. but the most used one is introducing weights in the Loss Function. And I found several formula to calculate weights such us:
wj=n_samples / (n_classes * n_samplesj)
or wj=1/n_samplesj</p>
<p>which is the best one?</p>
Answer: <p>I really don't suggest Under/Oversampling as it would change the distribution of dataset. we should consider distribution as a useful feature of dataset. so I think the weighted loss would have better performance in most cases. if you're using TF/Keras, <a href="https://www.tensorflow.org/tutorials/structured_data/imbalanced_data#class_weights" rel="nofollow noreferrer">this link</a> would be useful. you can use a variety of loss functions, like the below one, to apply the weight.</p>
<pre><code>tf.nn.weighted_cross_entropy_with_logits(
labels, logits, pos_weight, name=None
)
</code></pre>
<blockquote>
<p>A value pos_weight > 1 decreases the false negative count, hence increasing the recall. Conversely setting pos_weight < 1 decreases the false positive count and increases the precision.</p>
</blockquote>
|
https://datascience.stackexchange.com/questions/93873/class-weights-formula-for-imbalanced-dataset
|
Question: <p>I work in the medical domain, so class imbalance is the rule and not the exception. While I know Python has packages for class imbalance, I don't see an option in Orange for e.g. a SMOTE widget. I have read other threads in Stack Exchange regarding this, but I have not found an answer to how to tackle class imbalance in Orange without resorting to Python programming. Thanks</p>
Answer: <p>You can add <code>class_weights</code> with dictionary containing class weights, e.g.:</p>
<pre><code>class_weight = {0: 1., 1: 20.}
</code></pre>
<p>While <code>SMOTE</code> can be used to synthesize new examples for the minority class (the process is called oversampling) in order to get equal weights.</p>
<p>For <code>Orange</code> please check this <a href="https://datascience.stackexchange.com/questions/30206/scripting-code-for-class-imbalance-in-biolabs-orange">link</a>.</p>
<p>Please, provide more information so that we can help you.</p>
|
https://datascience.stackexchange.com/questions/89726/handling-imbalanced-datasets-in-orange
|
Question: <p>I’m working with an imbalanced dataset to predict strokes, where the positive class (stroke occurrence) is significantly underrepresented. Initially, I used logistic regression, but due to the class imbalance, I switched to a Random Forest model. After applying techniques such as random oversampling and adjusting the classification threshold, I've managed to improve my recall to approximately 61.3%. However, I am still facing a high false positive rate (178 instances) in my confusion matrix, which negatively impacts precision (17.6%). What additional strategies can I explore to further enhance precision while maintaining a good recall?</p>
Answer: <p>You can generally try:</p>
<ul>
<li>using a metric that takes the imbalance into account</li>
<li>class weights</li>
<li>better algorithms (gbdts)</li>
<li>tunning the prediction threshold or using continuous prediction directly</li>
</ul>
|
https://datascience.stackexchange.com/questions/130596/imbalanced-class-in-my-dataset
|
Question: <p>As an exercise, I'm trying to translate a model written in Keras (<a href="https://github.com/CVxTz/ECG_Heartbeat_Classification/blob/master/code/baseline_mitbih.py" rel="nofollow noreferrer">https://github.com/CVxTz/ECG_Heartbeat_Classification/blob/master/code/baseline_mitbih.py</a>) into Pytorch code. I realize in Keras much of the training part is abstracted into the function <code>model.fit()</code> function, while in Pytorch one has to be explicit. The dataset that is used to train the aforementioned model can be found on kaggle (/kaggle/input/heartbeat/mitbih_test.csv).By the looks of it the data is imbalanced towards one of the five classes.</p>
<p>Converting the model to Pytorch is rather simple, but writing a good training routine has proved to be challenging. A standard method to circumvent dataset imbalance is using weighted cross entropy loss. I computed the <code>class_weights</code> using <code>sklearn</code>'s <code>compute_class_weight_function</code> which was then fed to the <code>CrossEntropyLoss</code> function. However, this approach was not fruitful. My code for the training routine is given below:</p>
<pre><code># Hyperparameters
input_dim = 187 # Original time series length
num_classes = 5 # Number of output classes
# Instantiate the model
model = Model(num_classes)
# print(model)
model.to(device)
# Define loss function and optimizer
class_weights=class_weight.compute_class_weight('balanced',classes=np.unique(Y),y=Y.numpy())
class_weights=torch.tensor(class_weights,dtype=torch.float64).to(device)
criterion = nn.CrossEntropyLoss(weight=class_weights)
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
n_epochs = 1000
for epoch in range(n_epochs):
model.train()
last_loss = 0
running_loss = 0
for i, (X_batch, Y_batch) in enumerate(train_loader):
X_batch = X_batch.to(device)
Y_batch = Y_batch.to(device)
output = model(X_batch)
loss = criterion(output, Y_batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
running_loss += loss.item()
if i % 200 == 199:
last_loss = running_loss / 200 # loss per batch
print(' batch {} loss: {}'.format(i + 1, last_loss))
running_loss = 0.
</code></pre>
<p>On the Keras side, simply calling <code>model.fit(X, Y)</code> does the trick, where <code>X</code> and <code>Y</code> are the training data and targets respectively. Does this function do something special under the hood that I am missing?</p>
Answer:
|
https://datascience.stackexchange.com/questions/130193/understanding-the-model-fit-function-in-keras-and-imbalanced-datasets
|
Question: <p>I am building a binary classification model which has 17K values as class A and 10K values as class B. I want to know when a dataset can face the issues of "IMBALANCED Dataset" ?</p>
Answer: <p>In general there will be not a hard rule about this, but this dataset seems to be like balanced.
The point about disbalanced is that you have to keep in mind that the accuracy of your model will have a different starting point. For this python has the function to run a baseline with dummy classification. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html</a>. This gives you a good indication what is your baseline (if you choose the the strategy to most_frequent). In your case, any prediction model which always forecast class A, would have a accuracy of: 17/(10+17) = 0,6296... , so any binary classification with a score under this value would be really bad</p>
|
https://datascience.stackexchange.com/questions/53923/around-how-much-difference-between-two-classes-can-be-accounted-as-an-imbalanced
|
Question: <p>I'm dealing with an imbalanced dataset for binary classification (about 70% to 30%). I was wondering what is the best way to optimize the F1 score for such a task when using a convolutional neural net.</p>
<p>As of now, I'm sampling the dataset in order to create a balanced training set and am using the mean of softmax_cross_entropy_with_logits (from tf) with a regularization term as my loss.</p>
<p>How can I optimize for the F1 score? As it isn't convex I can't just plug it in as my loss, right? Most papers I found mentioned finding the best threshold. However, these were relatively old, is there something better which can be done for convolutional neural nets ?</p>
Answer: <p>I have <a href="http://pong.inescporto.pt/~rpcruz/ijcnn2016/imbalance.pdf" rel="nofollow noreferrer">a paper</a> where we try to maximize F1 score by using different techniques. We hoped that a ranking algorithm like RankNet would be able to get better F1 score than the others. But as you can see looking at our table, regular neural networks, without even using a cost matrix, were good enough. Creating synthetic samples until classes were balanced and even using MetaCost was also largely irrelevant.</p>
<p><a href="https://i.sstatic.net/UGp03.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UGp03.png" alt="F1 maximization table"></a></p>
<p>We did have a F1 gain when using RankNet, but that was likely due to our post-processing where we convert the ranking score into classes. But that is a pain. I think you can get similar results by, instead of using 0.5 as your threshold for choosing the positive class, choosing a threshold that maximizes the F1 score by just using the training data.</p>
<p>After working on class imbalance for awhile, I think this topic is a great way to get many publications easily, but, in the real world, a post-processing step and/or using a cost matrix to balance priors is more than enough.</p>
<p>ps: Please do not take this results as holy grail. Neural networks are notoriously difficult to optimize, especially across a range of very different datasets. Some cross validation was performed as mentioned in the paper, but, due to lack of time, not as much as we should have. And we did not allow that many iterations. I would try in your own code to introduce weights and some simple things to see if it makes a difference. Do let me know how it works please.</p>
|
https://datascience.stackexchange.com/questions/15795/f1-maximization-with-convolutional-neural-net-for-an-imbalanced-dataset
|
Question: <p>I'm facing a problem about making a classification on a dataset. The target variable is binary (with 2 classes, 0 and 1). I have 8,161 samples in the training dataset. And for each class, I have:</p>
<ul>
<li>class 0: 6,008 samples, 73.6% of total numbers.</li>
<li>class 1: 2,153 samples, 26.4%</li>
</ul>
<p>My questions are:</p>
<ul>
<li><p>In this case, should I consider the dataset I used as an imbalanced dataset?</p>
</li>
<li><p>If it was, should I process the data before using RandomForest to make a prediction?</p>
</li>
<li><p>If it was not an imbalanced dataset, could somebody tell me in which situation (like what ratio for each class) I could consider a dataset as imbalanced?</p>
</li>
</ul>
Answer: <p>Intuitively, it seems like an imbalanced dataset to have ~75/25 ratio of class labels.</p>
<p>If you want to take a look at it theoretically, you can do a hypothesis test. For a sample size of 8161, you can assume that the dataset is 50/50 as null hypothesis and then compute the probability that a number extreme as 6008 or more of them belong to one class as p-value and then try to reject the null hypothesis if the p value is low (less than 0.05 or 0.01 as per choice.)</p>
<p>This can be done using a binomial distribution.</p>
|
https://datascience.stackexchange.com/questions/87933/in-which-situation-should-we-consider-a-dataset-as-imbalanced
|
Question: <p>I am confused whether to use f1 score with 'micro' average or 'macro' average for better evaluation.
Given my dataset is highly imbalanced(600:100000)</p>
Answer: <p>To summarise this <a href="https://datascience.stackexchange.com/questions/15989/micro-average-vs-macro-average-performance-in-a-multiclass-classification-settin">answer</a>,</p>
<p>Macro calculates and F1 score for each class then averages them.</p>
<p>Micro calculates the recall/precision for each class, averages them then calculates the F1 score.</p>
<p>Micro average is preferable in a multi class situation where one class heavily outweighs the others.</p>
|
https://datascience.stackexchange.com/questions/58008/choice-of-f1-score-for-highly-imbalanced-dataset
|
Question: <p>We have a very imbalanced dataset (2% of class 1). To the best of our knowledge, there is no baseline in the literature to the problem we want to solve - so we thought of comparing our performance to a random classifier. We evaluate our model as a combination of precision and recall - we vary the threshold at which data points are classified as 1 and compute the rolling threshold and recall. We could use F1-score as well.</p>
<p>What would be an acceptable way to define a random predictor that we can compare to our model such that the comparison is as fair as possible?</p>
Answer: <p>You have <span class="math-container">$98\%$</span> in one class, right? This means that, knowing nothing about the data, you should be able to get <span class="math-container">$98\%$</span> of them right by guessing that majority class. If you get <span class="math-container">$97\%$</span> of them right, that sounds like an <span class="math-container">$\text{A}$</span> in school and thus a good model, but the model does worse than randomly guessing!</p>
<p>Better yet, compare using proper scoring rules like log loss (crossentropy) or Brier score, against a model that always predicts the prior probability of <span class="math-container">$P(y=1) = 0.02$</span>. This is analogous to how <span class="math-container">$R^2$</span> works in linear regression, by always guessing the mean of the <span class="math-container">$y$</span> variable. In your case, the mean of the <span class="math-container">$y$</span> variable is the class ratio. If you can't beat the model that always guesses <span class="math-container">$P(y=1) = 0.02$</span>, perhaps you have a poor model. (Specifics would depend on the misclassification costs, which you might or might not know.)</p>
<p><span class="math-container">$$\text{Log Loss}\\
L(y, \hat y) = -\frac{1}{N}\sum_{i = 1}^N \bigg( y_i\log(\hat y_i) + (1 - y_i)\log(1 - \hat y_i) \bigg)$$</span>
<span class="math-container">$$
\text{Brier Score}\\
L(y, \hat y) = \frac{1}{N}\sum_{i = 1}^N \bigg(y_i - \hat y_i\bigg)^2
$$</span></p>
<p>This assumes your <span class="math-container">$y_i\in\{0, 1\}$</span>. If you use <span class="math-container">$y_i\in\{-1. 1\}$</span>, you would have to modify the loss functions or change how you label your categories. The <span class="math-container">$\hat y_i$</span> values are probabilities. There are issues with the log loss if you predict a probability of <span class="math-container">$0$</span> or <span class="math-container">$1$</span>. Some see this as an upside of log loss, while others see it as a downside.</p>
<p><a href="https://stats.stackexchange.com/questions/357466/are-unbalanced-datasets-problematic-and-how-does-oversampling-purport-to-he">This kind of evaluation of the probability outputs is why statisticians do not see class imbalance as an issue.</a></p>
|
https://datascience.stackexchange.com/questions/70155/binary-classification-problem-with-imbalanced-dataset-how-to-compare-to-random
|
Question: <p>I have a small dataset with 300 rows and an imbalanced class distribution (35% positives). When I fit a logistic regression model, it consistently performs worse than random chance. I’m using stratified cross-validation to evaluate performance, but I’ve noticed a significant variance in results depending on the data splits.</p>
<p>My current procedure is as follows:</p>
<ol>
<li>Set aside a holdout test set using stratified k-fold cross-validation.</li>
<li>Use GridSearchCV on the training data to identify the best
hyperparameters for a tree-based model.</li>
<li>Calculate accuracy on the test set.</li>
</ol>
<p>However, I’ve encountered a problem: Depending on which test set I use, the logistic regression model can outperform the tree-based model selected by GridSearchCV. This seems counterintuitive, as logistic regression has consistently underperformed compared to random chance when evaluated on the full dataset.</p>
<p>Given these observations, I’m concerned that I cannot trust the performance of the holdout test set as an unbiased estimate of the best model. How should I adjust my evaluation procedure to ensure more reliable results, especially when working with such a small and imbalanced dataset?</p>
<p>What strategies would you recommend to address the high variance in model performance across different test splits?</p>
Answer: <p>Tree-based models tends to overfit on any data which is accessible. LR can generalise better. It's not always possible to achive good model score in real life (not Kaggle competition). Sometimes it's better to have worse score, but more consistent across different parts of data.</p>
<p>You can use regularisation. Or optimise score in such way, so it have no such big variation across parts of your data. So, you can trust this score, it's more stable. Cross-validation is often useful. And in case you have time-dependent data, you should use different kind of cross-validation, which utilize time factor properly.</p>
|
https://datascience.stackexchange.com/questions/130738/problem-logistic-regression-vs-tree-based-model-performance-on-small-imbalance
|
Question: <p>Now I have a task to classify the imbalanced time series datasets using ML classifiers, such as Logistic Regression, Decision Tree, SVM, and KNN. I am not allowed to use the Deep Learning tools, such as CNN and RNN. The time series data is measurements of the Force-Displacement Curve from a production line. The dataset is extremely imbalanced (minority class: majority class= 1:100). So I want to use Data Augmentation techniques to enlarge the size of the minority class, in order to optimize the performance of the classifiers and avoid overfitting.</p>
<p>I have tried many tools in feature-space, such as oversampling, undersampling, SMOTE, ADASYN and so on. But their performance is not so perfect. And I wish to generate synthetic time series data using Data Augmentation techniques, based on the initial data.
Similar to Image Recognition, I have also tried the exiting methods which have been applied to images, such as scaling, rotation, and jittering. But they are also not so useful.</p>
<p>So I want to ask if there are any other DA techniques to generate synthetic time series data. I have only some initial ideas, such as using DTW, Fournier Transform, Markov Chain and so on, but no papers or code about applying them.</p>
<p>Can anyone help me? I really appreciate your help. Thank you!</p>
Answer:
|
https://datascience.stackexchange.com/questions/62838/data-augmentation-techniques-for-classification-of-imbalanced-time-series-datase
|
Question: <p>I am performing a Binary Classification over an <strong>imbalanced dataset</strong>:<br />
0: 16,263<br />
1: 214</p>
<p>I have used multiple oversampling, undersampling, and combination techniques, below are the results that I have obtained:
I obtained this plots thanks to this piece of code:</p>
<pre><code>def plot_resampling(X, y, sampler, ax, title=None):
X_res, y_res = sampler.fit_resample(X, y)
ax.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
if title is None:
title = f"Resampling with {sampler.__class__.__name__}"
ax.set_title(title)
sns.despine(ax=ax, offset=10)
</code></pre>
<p><em><strong>Clarification: The X and y are the X_train and y_train and I used it to show the distribution of my data points before and after the resampling.</strong></em></p>
<p><a href="https://i.sstatic.net/NiRuq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NiRuq.png" alt="Comparison Initial Dataset and multiple oversampling techniques" /></a></p>
<p><strong>For the RandomUnderSampler, the first one is without replacement and the second one is with replacement=True</strong><br />
<a href="https://i.sstatic.net/IJri5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IJri5.png" alt="Comparison Initial Dataset and multiple oversampling techniques" /></a></p>
<p><a href="https://i.sstatic.net/KpNx0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KpNx0.png" alt="Use of Combination techniques" /></a></p>
<p>You need to know also that I have <strong>multiple outliers in my dataset</strong>, and hence, multiple columns are skewed, so I chose to use models that are not sensitive to skewness like:</p>
<ul>
<li>SVC</li>
<li>Naive Bayes Classifier</li>
<li>Ensemble XGboost</li>
<li>KNN</li>
</ul>
<p>For now, the best result that I have obtained is with <strong>SVC(kernel = "rbf")</strong> and using the <strong>SMOTE technique</strong>(Of course the sampling is only performed on the training dataset since the test one should represent the real population):</p>
<ul>
<li><strong>Test Accuracy: 0.75</strong></li>
<li><strong>Training Accuracy: 0.88</strong></li>
</ul>
<p>But the classification report is not good, the <strong>f1-score is 0.51</strong>, there is a <strong>real issue with the 1 class</strong> even after the resampling!! as you can see below:<br />
<a href="https://i.sstatic.net/EMjuC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EMjuC.png" alt="enter image description here" /></a><br />
Here is also the Confusion Matrix:<br />
<a href="https://i.sstatic.net/8GRjf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8GRjf.png" alt="enter image description here" /></a><br />
Can you please help me improve the f1 score, what is your analysis of the situation, and what are your suggestions?</p>
Answer:
|
https://datascience.stackexchange.com/questions/112720/low-f1-score-due-to-imbalanced-dataset-even-after-resampling
|
Question: <p>I have few dataset to experiment classification(Multi-class). These datasets are about 400GB. I wanted to know whether the dataset is balanced or imbalanced. How to know that dataset is balance or imbalanced using any scientific way?</p>
Answer: <p>Typically, the representation of each class in a multi-classification problem should be equal. Say if there are 4 classes, then the ratio of count of samples in each class should ideally be n:n:n:n, most classification data sets do not have exactly same number of sample count in each class, which is fine and a lit bit of difference often does not matter. But if the difference is huge, say for example 100:5:9:13 then it matters and it is an imbalanced dataset.</p>
<p>coming to 400 GB of data to read - Depending on the type of your file, you can read it in chunks and then read and save the target variable( the one which has multi class labels) in another variable. </p>
<p>You can visualize this variable (containing target) using a bar chart which will show you the count of variables for each class. Along with that you can also calculate the distribution of your classes to get better understanding of data. </p>
|
https://datascience.stackexchange.com/questions/61657/how-to-find-whether-a-dataset-is-blanced-or-imbalanced
|
Question: <p>Reading the following article: <a href="https://kiwidamien.github.io/how-to-do-cross-validation-when-upsampling-data.html" rel="nofollow noreferrer">https://kiwidamien.github.io/how-to-do-cross-validation-when-upsampling-data.html</a></p>
<p>There is an explanation of how to use <code>from imblearn.pipeline import make_pipeline</code> in order to perform a cross-validation on an imbalanced dataset while avoiding memory leakage.</p>
<p>Here I copy the code used in the notebook linked by the article:</p>
<pre><code>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=45)
rf = RandomForestClassifier(n_estimators=100, random_state=13)
imba_pipeline = make_pipeline(SMOTE(random_state=42),
RandomForestClassifier(n_estimators=100, random_state=13))
cross_val_score(imba_pipeline, X_train, y_train, scoring='recall', cv=kf)
new_params = {'randomforestclassifier__' + key: params[key] for key in params}
grid_imba = GridSearchCV(imba_pipeline, param_grid=new_params, cv=kf, scoring='recall',
return_train_score=True)
grid_imba.fit(X_train, y_train);
grid_imba.best_params_
grid_imba.best_score_
</code></pre>
<p>I do not understand why using the pipeline avoids the problem of building a validation set that, due to a possible oversampling <em>before</em> splitting, might cause memory leakage problems.</p>
<p>Secondy, can we use the pipeline for the same purpose but using the original data-set "X,y" as parameters for the arguments of the functions in the pipeline? So in this way:</p>
<pre><code>imba_pipeline = make_pipeline(SMOTE(random_state=42),
RandomForestClassifier(n_estimators=100, random_state=13))
cross_val_score(imba_pipeline, X, y, scoring='recall', cv=kf)
new_params = {'randomforestclassifier__' + key: params[key] for key in params}
grid_imba = GridSearchCV(imba_pipeline, param_grid=new_params, cv=kf, scoring='recall',
return_train_score=True)
grid_imba.fit(X, y);
grid_imba.best_params_
grid_imba.best_score_
</code></pre>
Answer: <p>The page linked already gives a really good explanation:</p>
<blockquote>
<p>To see why this is an issue, consider the simplest method of
over-sampling (namely, copying the data point). Let's say every data
point from the minority class is copied 6 times before making the
splits. If we did a 3-fold validation, each fold has (on average) 2
copies of each point! If our classifier overfits by memorizing its
training set, it should be able to get a perfect score on the
validation set! Our cross-validation will choose the model that
overfits the most. We see that CV chose the deepest trees it could!</p>
</blockquote>
<p>The main point is that you need to make sure that the data is first split into train/test by using the cross-validation before applying any upsampling methods. This can be achieved by using a pipeline since it makes sure that the upsampling and model fitting are combined and are applied only after the data is split for cross-validation. It would still be possible to do this without a pipeline by splitting the two steps and applying them manually but you'd have to do the cross-validation splitting yourself by using a using indices from <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html" rel="nofollow noreferrer"><code>sklearn.model_selection.KFold</code></a> (see the example provided) since <code>cross_val_score</code> and <code>GridSearchCV</code> have no option for this and only allow a single estimator (which itself can also be a pipeline of multiple steps).</p>
|
https://datascience.stackexchange.com/questions/106613/explaining-the-logic-behind-the-pipe-line-method-for-cross-validation-of-imbalan
|
Question: <p>My training data has extremely <strong>class imbalanced</strong> {0:872525,1:3335} with 100 features. I use xgboost to build classification model with bayessian optimisation to hypertune the model in range
<code>{learning rate:(0.001,0.1), min_split_loss:(0.10), max_depth:(3,70), min_child_weight:(1:20), max_delta_step:(1,20), subsample:(0:1), colsample_bytree:(0.5,1), lambda:(0,10), alpha:(0,10), scale_pos_weight:(1,262), n_estimator:(1,20)}</code>.</p>
<p>I also use binary:logistics as the objective model and roc_auc as the metrics with booster gbtree.
The cross validation score is 82.5%.
However, when I implemented the model to the testing data I got the score only
Roc_auc: 75.2%, pr_auc: 15%, log_loss: 0.046, and confusion matrix: [[19300 7],[103 14]].
I need helping to find the best way to increase the true possitive with tolerance false positive until 3 times actual positive.</p>
Answer: <p>Given an imbalanced dataset and focusing on <strong>increasing your true positive rate</strong>, it is quite relevant to use the right <strong>evaluation metric</strong> (the one used to validate the model being trained on each evaluation round).</p>
<p>In this case, I recommend you use <strong>Precision-Recall AUC instead of ROC AUC,</strong> so you force your model to focus on the minority class.
A nice post about it can be found <a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-imbalanced-classification/" rel="nofollow noreferrer">here</a></p>
<p>Another points to take into account could be:</p>
<ul>
<li><strong>increase</strong> the <strong>range</strong> of possible <strong>number of tree estimators</strong> in your hyperparameter tuning process</li>
<li>set the scale_pos_weight at about your (majority class samples number)/(minority class samples number)</li>
</ul>
|
https://datascience.stackexchange.com/questions/90015/hypertune-xgboost-to-dealing-with-imbalanced-dataset
|
Question: <p>I have some doubts regarding an analysis. I have a dataset with class imbalance. I am trying to investigate some information from that data, e.g., how many urls contain http or https protocols.
My results are as follows:</p>
<pre><code>http in dataset with class 1: 10
http in dataset with class 0: 109
https in dataset with class 1: 180
https in dataset with class 0: 1560
</code></pre>
<p>I am trying to build a classifier based on some features and the presence of protocols was supposed to be taken into account.
However, on the basis of the above results, what do you think I should say?
Does it make sense to say that the most websites having class 0 have an https protocol, even if I have a dataset with class imbalance?
For a model, I would consider resampling techniques. Should I work on this analysis (so make this conclusion) after the resampling, or it would make sense to check features importance with other tests (e.g., Pearson correlation, if it is appropriate in this case)?</p>
<p>Any suggestion would be greatly appreciated it.</p>
Answer: <p>What this shows is that the protocol is not a very discriminative feature:</p>
<ul>
<li>the probability of class 1 given http is 10/(109+10)=0.084</li>
<li>the probability of class 1 given https is 180/(180+1560)=0.103</li>
</ul>
<p>If these conditional probabilities were very different this feature would be more helpful to predict the class, but they differ only slightly. Note that the feature might still be useful, but it doesn't have a huge impact on its own. In case you're interested to know if the difference is significant (i.e. not due to chance), you could do a <a href="https://en.wikipedia.org/wiki/Chi-squared_test" rel="nofollow noreferrer">chi-square test</a>.</p>
<blockquote>
<p>Does it make sense to say that the most websites having class 0 have an https protocol, even if I have a dataset with class imbalance?</p>
</blockquote>
<p>It is factually correct, but most websites having class 1 also have https so it's not a very useful information (and on its own this information might be confusing for some readers).</p>
<blockquote>
<p>For a model, I would consider resampling techniques. Should I work on this after the resampling, or it would make sense to check features importance with other tests (e.g., Pearson correlation, if it his appropriate in this case)?</p>
</blockquote>
<p>Feature selection can done either before or after resampling, it doesn't matter. The two things are independent of each other because the level of correlation between a feature and the class is independent from the proportion of the class.</p>
<p>I don't think Pearson correlation is good for categorical variables. I think conditional entropy would be more appropriate here (not 100% sure, there might be other options).</p>
|
https://datascience.stackexchange.com/questions/89073/features-selection-in-imbalanced-dataset
|
Question: <p>I have a small dataset of 150 records with 25 features (too small to do train/test).
I'm using nested cv for both hyperparameter tuning and feature selection. 10cv in the outer loop, 5 cv in the inner loop.
Eventually i'm getting 10 sets of hyperparameters and 10 sets of selected features.
If i'm publishing my results, how eventually would i know which features should be selected for a model to be tried on an external data. (Currently i don't have another external data to test the model)</p>
<p>thank you</p>
Answer: <p>Assuming the feature selection method is always the same, on an external data (or final training set), you would simply apply the exact same method. The actual set of selected features does not matter.</p>
<p>If there was any difference in the selection method, for instance if you are selecting different number of features, you would do like with any other hyper-parameter: select the best model according to the nested CV process, then apply the same hyper-parameters (including for instance number of features) when training the final model.</p>
|
https://datascience.stackexchange.com/questions/85994/nested-cv-feature-selection
|
Question: <p>I have to perform predictive model over the dataset $D$ (with 1000 obs).
From $D$, I extract 700 obs for training $(T)$ and 300 obs for validation $( V )$.</p>
<p>I need to perform bootstrap or 10-fold cross validation sampling.</p>
<p>The question is which of these sets should I use?</p>
<ul>
<li><p>Divide $D$ in 10 subsets and alternate training and validation between them ? </p></li>
<li><p>Divide $T$ (the training subset) in 10 subsets and perform training/validation on those subsets? $V$ is used only for final validation.</p></li>
</ul>
Answer: <p>I recommend using the second option you presented. I would use $T$ with 10-fold CV to select my modeling technique and optimal tuning parameters. Take a look at what performed the best ("best" being the model that gives us the best error, but also doesn't have the error fluctuate too much from fold to fold). After selecting a model, you can use the model on $V$ to get a realistic error rate.</p>
<p>The reason I don't recommend the first option is: There are varying degrees of over fitting that can occur when going through model selection and model tuning, then using that same data to get an error rate. CV is a great way to limit this overfitting and it gives us a sense of performance variance which is great, but a classic hold-out validation set is the gold standard for model performance. In your case the first option might not be wrong (depends a lot on data/techniques), but if a hold-out validation set is available I would go for that.</p>
|
https://datascience.stackexchange.com/questions/11316/which-observation-to-use-when-doing-k-fold-validation-or-boostrap
|
Question: <p>Recently I have been using LightGBM as regressor in order to predict, on a dataset of 20 thousand observations and 40 variables.</p>
<p>I have two modes, <strong>1)</strong> Production and <strong>2)</strong> Testing. The first one just trains a model with the whole dataset. The second does the same with an 80% of the dataset and tests over the remaining 20% (80-20 done with train_test_split, from sklearn.model_selection, no seed used).</p>
<p>In both cases I show the <em>neg_mean_squared_error</em> at the end of the execution. In the first case for the whole dataset, in the second I get two values (training and testing)</p>
<p>I am shocked to see that while in the first case my error is around -10, in the second the values are -5 (training) and -5.3 (testing). An average value of my objective variable can be 80. I would expect to lose accuracy since I train with less data and then I test over a different sample.</p>
<p><strong>Question</strong>: There is any theoretical reason that explains that a 80-20 test gets a "better" neg_mean_squared_error than in the full data case? Or it has to be a (sneaky) bug in my code?</p>
Answer: <p>I cannot think about any theoretical reason. However:</p>
<ul>
<li>It may be the case that the neg_mean_squared_error is not correctly implemented. Try another metric, like Median or Mean Percentage Error and see if that continues to happen.</li>
<li>It may be related to how the data is distributed, but still that's not common.</li>
</ul>
<p>Lastly, I wouldn't put a model in production (if by that you mean deploying into a product, for example) without testing its performance in a test set, even if in another instance of the model, trained using cross validation, has good performance. One reason: it may be the case that a small part of the training data breaks your model, and does not generalise. </p>
|
https://datascience.stackexchange.com/questions/46430/80-20-better-than-full-dataset-for-lightgbm
|
Question: <p>For what I read the 5x2cv t test is</p>
<p>"a procedure for comparing the performance of two models (classifiers or regressors) that was proposed by Dietterich to address shortcomings in other methods such as the resampled paired t test and the k-fold cross-validated paired t test"</p>
<p>.</p>
<p>I am currently making some experiments with an unbalanced data set, which I balanced using SCUT and trained a set of different classifiers. The problem is a multiclass with three different classes to choose. I am applying a Multilayer Perceptron, a Decision Tree and a Random Forest and the results, after a 10-fold cross validation, are the following:</p>
<p>Multilayer Perceptron: 0.95 acc</p>
<p>Decision Tree: 0.93 acc</p>
<p>Random Forest: 0.935 acc</p>
<p>When I apply the 5x2cv t test I got the following results:</p>
<p>MLP and DT:</p>
<p>t-statistic 4.75</p>
<p>p-value 0.005</p>
<p>So, if I assume that for the tests I will have a value of alpha of 0.05 for rejecting the null hypothesis, which is that both algorithms perform well with the same database, then from the p-value I got I could reject the null hypothesis. This would mean that both models do not perform equally well, so it would be better to use MLP over the DT because of its higher accuracy.</p>
<p>When I do the same with the MLP and the RF I got the following results:</p>
<p>t-statistic: 2.46</p>
<p>p-value: 0.055</p>
<p>Here, I suppose that I can conclude that using MLP or RF for the current dataset is almost the same, because I failed to reject the null hypothesis. The question that I have here is if should I choose the RF even though the accuracy was lower?</p>
<p>The comparison with the DT and RF has the following values:</p>
<p>t-statistic: -2.49</p>
<p>p-value: 0.054</p>
<p>So I can reject the null hypothesis and said that there is difference between the use of the DT over the RF.</p>
<p>Are my conclusions correct?</p>
<p>Thanks</p>
Answer: <p>See, your conclusions appear to be correct, your statistical results explain your conclusions , i would say statistically speaking even with a P-value of 0.055 you still have an error rate of 15 to 25% that you may be accepting a wrong null hypothesis and maybe your alternate hypothesis is right , so combining knowledge of statistics with data science i will suggest you to use catboost(if you have some categorical features in your dataset it will give you a strong baseline prediction before you start tuning it) otherwise random forest is good any day and if you have a small dataset (e.g. less than 1500 instances in your training data) i would suggest use random forest any day over MLP because MLP based classifiers need more data to classify better with less data they tend to become bias towards your training data.But if you have a large enough dataset you can actually use MLP based classifier try some basuc feature selection techniques such as RFECV or feature_importanece_ function you can use contained in every model after you train it . And if at the end of the day you are still confused to which model to use i would suggest use all of them stack them and you will have something better.Making these decisions solely on the basis of statistics is tough because statistics puts everything into an abstract form that is a whole dataset being represented by 1 number thus it is always prone to certain errors thus i always prefer to combine my data science experiments with my statistical results and then only conclude about my results.Also while using statistical analysis a lot of things depend on your dataset i.e. is it big enough to draw meaningful conclusions out of it what might be the sampling error and many more things .Hope this helps.</p>
|
https://datascience.stackexchange.com/questions/56847/choosing-classifiers
|
Question: <p>So i'm doing <em>cross validation</em> and then i'm predicting using all the data on a test set ( a hold-out set ). My hold-out set has the <strong>same ratio</strong> on a column than the train ( seems thats how the test set was generated, a function that sampled it and tried to preserve the ratio for the <strong>target</strong> classes, and a <strong>particular column</strong> ) . My local CV is a bit lower than my score on the test set, and i think the problem is stemming from the fact that i'm using stratification only for 'y'. </p>
<p>Can lack of stratification of that feature be the reason of Cv & test scores aren't really close? </p>
<p>And if so how can i perform stratification for the target and a feature!
Thanks </p>
<p>Edit : i'm already doing stratification on the target since my data is imbalanced.</p>
Answer: <p>One idea would be to combine the two columns (one predictor and the target) and then stratify using the combined column.</p>
<p>Example: say for some observations, the target and the column take the following values: <code>target = [0,1,0]</code> and <code>column = [A,A,B]</code>. Then the combined column could look something like <code>[A0,A1,B0]</code> and could be used for stratification.</p>
<p><em>I'm obviously assuming that the predictor column is categorical - you might have to take a different approach for a continuous variable.</em></p>
|
https://datascience.stackexchange.com/questions/58557/cross-validation-while-preserving-a-column-not-the-target-distribution
|
Question: <p>My mentor wants me to write and submit an academic paper reporting a predictive model, but without any validation score.</p>
<p>Everything I have read in textbooks or the Internet says that this is wrong, but is there any case where only reporting a train score makes sense?</p>
<h3>Background</h3>
<p>The model was fit "by hand" by someone in our team, using a visual inspection of features extracted from our entire dataset. It is a linear model based on hand-crafted features extracted from some very nonlinear and high-dimensional data. The linear model is based on less than fifty features, but those features were extracted from thousands. We do not have any data left to use as validation.</p>
Answer: <p>The most likely issue here is to do with </p>
<blockquote>
<p>fifty features, but those features were extracted from thousands</p>
</blockquote>
<p>If those features were selected according to a pre-data-analysis theory, and other selections were not considered, then a linear model that fit the data might be strong proof that the theory was plausible.</p>
<p>However, a linear model that fits well due to selection from a large feature set <em>in order to make it fit</em> is very likely to be overfit. You absolutely need a hold-out test data set in this case, as you have used your initial data to form a hypothesis, and have no proof of validity at all.</p>
<p>I cannot advise you whether to submit the paper or not. There may be ways you can word it to make it clear that the work establishes a hypothesis and does not validate it (but without making a song and dance about the lack of rigour in validation, as then you are undermining your own submission). </p>
<p>I think that as long as you do not try to obfuscate the lack of follow up work, and present results so far accurately, then it is a fair submission - it may then get rejected if a reviewer wants to see some validation, or it may get accepted and there will need to be follow up work that either validates or refutes the model in a second paper. That might be your work, it might be another team's. </p>
<p>How good/bad those scenarios are depends on how your field works in general. Perhaps ask with some relevant details on <a href="https://academia.stackexchange.com/">https://academia.stackexchange.com/</a> to gauge your response, as in some ways this is a people problem - how to please your mentor whilst retaining pride in your work and progressing your career (which in turn depends on a mix of pleasing your supervisor and performing objectively good work). </p>
<p>Your mentor may still be open to discussing the technical merits of the work. Perhaps they have not fully understood the implications that you are seeing for how the model was constructed. However, they might fully understand this, and may be able to explain from their view the merits of publishing at an early pre-validation stage for this project.</p>
|
https://datascience.stackexchange.com/questions/60821/publish-without-validation-score
|
Question: <p>I've been running kfold cross validation with 10 folds and comparing it against a test set. Logging the score and the stdev along the way. </p>
<p>Once I wad happy with my model I then run the estimator through the cross validation with the full data (including the test set) but ... The standard deviation of the scores increases and the score decreased????</p>
<p>Is this normal? I assumed MORE data decreases variance ? Or is it just due to the randomness in the splits ?</p>
Answer: <p>The score decreasing and the standard deviation of the scores increases, as sample size increases, indicates overfitting to the smaller sample size. </p>
|
https://datascience.stackexchange.com/questions/68182/increasing-samples-increases-variance
|
Question: <p>When using "K-Fold Cross Validtion" for Neural Net, do we:</p>
<ol>
<li>Pick <strong>and save</strong> initial weights of the network randomly (let's call it $W_0$)</li>
<li>Split data into $N$ equal chunks</li>
<li>Train model on $N-1$ chunks, validating against the left-out chunk (the $K$'th chunk)</li>
<li><strong>Get validation error and revert the weights back to</strong> $W_0$</li>
<li>shift $K$ by 1 and repeat from 3.</li>
<li>Average-out the validtion errors, to get a much better understanding of how network will generalize using this data.</li>
<li><strong>Revert back to $W_0$ one last time, and train the network using the ENTIRE dataset</strong> </li>
</ol>
<hr>
<p><strong>Question 1:</strong></p>
<p>I realize 7 is possible, because we have a very good understanding of how network will generalize with the help of step 6. - Is this assumption correct?</p>
<p><strong>Question 2:</strong></p>
<p>Is reverting back to the initial $W_0$ a necessity, else we would overfit? (revert like we do in step 4. and 7.) </p>
<p><strong>Question 3, most important:</strong></p>
<p>Assume we've made it to step 7, and will train the model using ENTIRE data. By now, we don't intend to validate it after we will finish. In that case how do we know when to stop training the model during step 7? </p>
<p>Sure, we can train with same number of epochs as we did during Cross validation. But then how can we be sure that Cross Validation was trained with an appropriate number of epochs in the first place? </p>
<p>Please notice - during steps 3, 4, 5 we only had $K$'th chunk to evaluate Training vs Validation loss. $K$'th chunk is very small, so during the actual Cross-Validation it was unclear when to Early-Stop... To make things worse, it will be even more difficult in case of Leave-One-Out (also know as All-But-One), where K is simply made from a single training example</p>
Answer: <p>First, I would like to emphasize, that cross-validation on itself does not give you any insights about overfitting. This would require comparing training and validation errors over the epochs. Typically you make such comparison with your eye and you can start with one train/validation split.</p>
<p><strong>Question 1:</strong> By getting validation error N times, you develop a reasonable (whether it is very or not very good is a question) understanding of how your network will perform (= what error it will give) on the new unseen data. </p>
<p>Often you do cross validation as a part of grid search of hyper-parameters. Then averaging errors at step 6 is mainly for choosing the best hyper-parameters: you believe that the hyper-parameters are best if the corresponding network produces the smallest average validation error. Simultaneously this error is your estimation on what error the final model will give you on the new data.</p>
<p>If you want, you can proceed with your exploration and compare validation errors (for one and the same hyper-parameter set) with each other, calculate standard deviation in order to get further insights. </p>
<p>The concept "model generalizes well" is more related to the absence of overfitting. To make this conclusion, you need to compare train and validation errors. If they are close to each other, then the model generalizes well. This is not directly related to cross validation.</p>
<p><strong>Question 2:</strong> The only purpose to take the whole dataset is to train the model on more data. And more data is always good. On the other side, if you are happy with one of the models produced during cross-validation, you can take it.</p>
<p><strong>Question 3:</strong> You can take the number of epochs as one of the parameters in grid-search of hyper-parameters. This search usually goes with cross-validation inside. When at step 7 you take the whole data set, you take more data. Thus, overfitting, if at all, at this stage can only be reduced. If it bothers you, that each chunk is small, replace K-fold cross validation with, for example, K times 50/50 train/test splits. And I would never worry about leave-one-out. It was developed for small (very small) datasets. For Neural Net to be good, you typically need large or very large dataset.</p>
|
https://datascience.stackexchange.com/questions/28542/cross-validation-how-to-determine-when-to-early-stop
|
Question: <p>I have on my uni lecture notes that one of the n-fold cross-validation disadvantages is that it is very expensive to train this because this could take a long time if the dataset is very large. But they say that this is not the case if we use k-nearest neighbors classifier. I know to some extend what a k-nearest neighbors classifier does, it tries to calculate a distance between the current example to all it k neighbors and assign this current example the label of the nearest example in terms of distance to current example. But I still don't get the connection to why n-fold CV is not expensive in this case.</p>
<p>Some clarification on this question is appreciated! Thanks</p>
Answer: <p>Your understanding is correct, but for the point of interest what matters is that k-NN is a "lazy learner" (see explanations for example <a href="https://sebastianraschka.com/faq/docs/lazy-knn.html" rel="nofollow noreferrer">here</a> or <a href="https://datascienceguide.github.io/k-nearest-neighbor" rel="nofollow noreferrer">here</a>): training a k-NN model requires no computation, the training data is only stored as is. The computation happens at testing: any test instance needs to be compared to the instances in the training set to determine its label based on the closest ones. So the training is fast and the testing is slow, as opposed to most standard ML algorithms.</p>
<p>If one compares what happens in <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation" rel="nofollow noreferrer">k-fold CV</a> compared to what happens with a simple train-test split, assuming that the test set in the latter case has the same size as the full data used for CV:</p>
<ul>
<li>the training is repeated k times, so it takes much more time if the training stage is long.</li>
<li>applying the model is proportional to the number of instances. If this number is the same in the two cases, there's no difference.</li>
</ul>
<p>Thus there is little or difference in time for k-NN, as opposed to most other learning methods.</p>
|
https://datascience.stackexchange.com/questions/109729/why-is-n-fold-cross-validation-not-expensive-for-k-nearest-neighbours
|
Question: <p>You split the data in k subsamples. Train it on k-1 subsamples, test it on kth subsample, record the performance with some error merric.</p>
<p>Do it k times for each of the k subsamples, record the error each time.
Then choose the model with the lowest error?
Is it the same as ensemble technique?</p>
Answer: <p>Imagine you have 1500 labeled data points, and you want to estimate how well some classifier will work on new data. One (naive) method would be to train a model with all 1500 of your data points, and then check how many of the 1500 data points were classified correctly. This is not likely to give a good estimate of the performance on new data, because new data was not used to test the model. Some models like decision trees and neural networks will often be able to get 100% accuracy on the training data, but perform much worse on new data.</p>
<p>So you think to yourself that you will split the data into two sets - a training set which you will build a model with, and a testing set that you will use to evaluate the model. Lets say you decided to train the model with 1000 of your examples, and evaluate with 500. This should give a reasonable estimate of how well your model will perform on new data, but it seems a bit limited; after all, one third of your data has not been used for training at all! We only have predictions for the 500 test samples - if these ones randomly happened to be easier to classify correctly on average, then our performance estimate is overly optimistic.</p>
<p>Cross validation is a way to address this. Lets set $k=3$, so the data is split into three sets of 500 points (A, B and C). Use A & B to train a model, and get predictions for C with this model. Use B & C to train a model, to get predictions for A. Finally, use A & C to train a model, and get predictions for B. Now we have a prediction for every point in our labeled data that came from a model trained on different data. By averaging the performance of each of these models, we can end up with a better estimate of how well the model will perform on new data.</p>
<p>Note that you should then re-train your model using all 1500 labeled points if you want to apply it to new data. Cross validation is only for estimating the performance of this new model. Also if your data is large enough, cross validation is probably unnecessary and you could just make a single train/test or train/valid/test split. </p>
|
https://datascience.stackexchange.com/questions/26669/how-does-k-fold-cross-validation-work
|
Question: <p>let me begin by saying that I understand how to build a stacked ensemble by using cross-validation to generate out-of-fold predictions for the base learners to generate meta-features. My question is about the methodology when cross-validating the entire stacked ensemble to check generalization error.</p>
<p>To eliminate any confusion, I'm going to call the cross-validation to generate out of fold predictions for the base learner CV A, while I'll call the cross-validation of the entire stacking ensemble CV B.</p>
<p>When I do CV B, is it valid to do CV A just once and use those out of fold predictions for the entire CV B process? Or do I have to keep doing CV A and generate new out of fold predictions during each fold of CV B?</p>
<p>Normally, I'd think that there'd be some data leakage in the first method, but one could also reason out that since the out of fold predictions are taken, well, out of fold, that issue is taken care of. The main reason I'm asking this is because doing the second method would surely remove any data leakage but there would be an order of magnitude of additional computational complexity involved.</p>
Answer: <p>I posted this same question on Reddit and someone was kind enough to answer</p>
<p>By <a href="https://www.reddit.com/user/patrickSwayzeNU" rel="nofollow noreferrer">https://www.reddit.com/user/patrickSwayzeNU</a></p>
<blockquote>
<p>This</p>
<blockquote>
<p>When I do CV B, is it valid to do CV A just once and use those out of fold predictions for the entire CV B process?</p>
<p>Normally, I'd think that there'd be some data leakage in the first method, but one could also reason out that since the out of fold predictions are taken, well, out of fold, that issue is taken care of.</p>
</blockquote>
<p>Yes, your data set created by CV A is now "good as new".</p>
</blockquote>
|
https://datascience.stackexchange.com/questions/17317/cross-validation-of-a-cross-validated-stacking-ensemble
|
Question: <p>My textbook states that k-fold cross-validation is a resampling technique that is useful for estimating generalization error in a data-poor setting.</p>
<blockquote>
<p>Ideally, if we had enough data, we would set aside a validation set and use it to assess the performance of our prediction model. Since data are often scarce, this is usually not possible. To finesse the problem, K-fold cross- validation uses part of the available data to fit the model, and a different part to test it. (<em>Hastie, The Elements of Statistical Learning, Section 7.10, page 241.</em>)</p>
</blockquote>
<p>For a machine learning project, I used Scikit-learn's grid-search cv method to find the optimal hyper-parameters for my random forest. The Scikit-learn docs <a href="https://scikit-learn.org/stable/modules/grid_search.html" rel="nofollow noreferrer">recommend exactly this</a>:</p>
<blockquote>
<p>It is possible and recommended to search the hyper-parameter space for the best cross validation score. ... Two generic approaches to parameter search are provided in scikit-learn: for given values, GridSearchCV exhaustively considers all parameter combinations.</p>
</blockquote>
<p>However, my professor disagreed: he asked me why I used cross-validation in a data-rich context (Fashion-MNIST dataset).</p>
<p>Was grid-search CV inappropriate in a data-rich problem? I don't know how to resolve this discrepancy, and my professor's feedback was not particularly instructive.</p>
Answer: <p>When you are doing hyperparameter tuning on Testing data , it puts you at risk of introducing Bias as training data should act as unseen data and no optimisation should be done on that. So to avoid this scenario completly you can follow two approach:</p>
<ol>
<li>Divide your training data into train and validation. Where Validation data will help you in tuning the hyperparameters.
If you have lot of data you can follow this approach and once best hyperparam are found train the final model on training data completly.</li>
</ol>
<p>I also dont see any mistake in using CV even in case of data rich components.</p>
|
https://datascience.stackexchange.com/questions/108474/should-i-use-gridsearch-cv-for-hyper-parameter-tuning-in-a-data-rich-context
|
Question: <p>In google's crash course on <a href="https://developers.google.com/machine-learning/crash-course/validation/another-partition" rel="nofollow noreferrer">ML</a>, I have read an interesting tip on train&validation sets.
they say</p>
<blockquote>
<p>'Test sets and validation sets "wear out" with repeated use. That is,
the more you use the same data to make decisions about hyperparameter
settings or other model improvements, the less confidence you'll have
that these results actually generalize to new, unseen data.</p>
<p>If possible, it's a good idea to collect more data to "refresh" the
test set and validation set. Starting anew is a great reset.</p>
</blockquote>
<p>how is that possible? how and why should it wear out? And what does 'wearing out of the data' mean to begin with?' And can I solve this by randomly re-partitioning the sets into three(train-test-cv) for different models rather than using the same partitions for all?</p>
Answer: <p>The purpose of splitting our data into training, validation, and test sets is to evaluate our models with data that they have not seen before and to directly compare them (and to choose the best model based on that comparison).</p>
<p>However, the more we use the test and validation sets to compare models or choose hyperparameters, the more we are relying on them to choose models that perform the best on them, that is, our models begin to depend indirectly (through us selecting them) on the test set, therefore defeating their initial purpose of evaluating our models with data they have not seen before.</p>
<p>The problem with randomly re-partitioning the sets into different train/validation/test sets for each problem is that it does not enable you to directly compare the performance of the different models, therefore defeating the very purpose of having a test set.</p>
<p>A solution is proposed in the paragraph you cited:</p>
<blockquote>
<p>If possible, it's a good idea to collect more data to "refresh" the test set and validation set. Starting anew is a great reset.</p>
</blockquote>
|
https://datascience.stackexchange.com/questions/118122/how-and-why-do-training-and-cross-validations-sets-wear-out-in-time
|
Question: <p>I have seen this in two Papers:</p>
<p>The authors use 10 fold cross validation, and then present the results from this validation or even odder the results from the best Fold as their modelling Result. </p>
<p>there has been no testing data put aside to validate the final model. These are peer reviewed papers i am talking about. Is this right to do ? Can one even cite such sources?</p>
Answer: <p>The key question is</p>
<blockquote>
<p>Is K-fold cross validation is used to select the final model (or algorithm)?</p>
</blockquote>
<ol>
<li><p>If yes, as you said, then the final model should be tested on an extra set that has no overlap with the data used in K-fold CV (i.e. a test set).</p></li>
<li><p>If no, the average score reported from K-fold CV is the final test score, no extra set is required.</p></li>
</ol>
<p>Therefore, if authors only picked the best model from all K models, it should have been tested on an extra set. The score of model on the validation fold (from K-fold CV) is not acceptable.</p>
<p>Also, here is <a href="https://datascience.stackexchange.com/q/47263/67328">a related post on this site</a> (my answer) that goes into more detail about test and validation sets (scores).</p>
<p><strong>EDIT</strong>:</p>
<p>I have found a similar question on <a href="https://stats.stackexchange.com/q/225949/195246">stats.stackexchange.com</a>. Also, <a href="https://stats.stackexchange.com/questions/225949/do-we-need-a-test-set-when-using-k-fold-cross-validation#comment427962_225957">this comment by amoeba</a> suggestions "<a href="https://stats.stackexchange.com/q/65128/195246">nested CV</a>" instead of "CV + test set", which I think it is worth fleshing out here.</p>
<p><strong>K-fold CV evaluation</strong></p>
<pre><code>1. For k = [1,..,K]
1. tr = (K-1)/K of data, ts = 1/K of data
2. m[k] = model trained using tr (can be further split into tr2 + v)
3. score[k] = score of m[k] on ts
3. Test score = average of score[1],...,score[K]
</code></pre>
<p><strong>K-fold CV selection and evaluation</strong></p>
<pre><code>1. tr = 80% of data, ts = 20% of data (or some other ratio)
2. For k = [1,..,K]
1. tr2 = (K-1)/K of tr, v = 1/K of tr
2. m[k] = model trained using tr2 (can be further split into tr3 + v2)
3. score[k] = score of m[k] on v
3. M = best of m[1],...,m[K]
4. Test score = score of M on ts
</code></pre>
<p><strong>Nested k-fold CV selection and evaluation</strong></p>
<pre><code>1. For k = [1,..,K]
1. tr = (K-1)/K of data, ts = 1/K of data
2. For k2 = [1,..,K2]
1. tr2 = (K2-1)/K2 of tr, v = 1/K2 of tr
2. m[k2] = model trained using tr2 (can be further split into tr3 + v2)
3. score[k2] = score of m[k2] on v
3. M = best of m[1],...,m[K2]
4. score[k] = score of M on ts
2. Test score = average of score[1],...,score[K]
</code></pre>
<p>Note that in these algorithms, <code>model trained</code> includes parameter learning, hyper-parameter tuning, and model selection (of course, except for the outermost model selection). For example, for selecting between hyper-parameters 8 and 12, we need a deeper loop inside <code>model trained</code>.</p>
|
https://datascience.stackexchange.com/questions/49571/can-we-use-k-fold-cross-validation-without-any-extra-excluded-test-set
|
Question: <p>We do the following:</p>
<ol>
<li>split <code>data_all</code> into K folds, each consisting of <code>data_train_k</code> and <code>data_test_k</code> where k = 0, ... K-1.</li>
<li>for each k in 0, ... K-1, split <code>data_train_k</code> into M folds each consisting of <code>data_train_k,m</code> and <code>data_eval_k,m</code> where m = 0, ... M-1. Then perform hyperparameter tuning via cross-validation using the M folds. We validate the optimized model using <code>data_test_k</code>. Now we have K tuned models with cross-validated metric, like:</li>
</ol>
<pre><code>k | avg eval score on M folds | std of score on M folds | test score
0 | 0.92 | 0.05 | 0.93
...
K-1|0.89 | 0.03 | 0.88
</code></pre>
<ol start="3">
<li>compute average <code>test_score</code> - this is <span class="math-container">$\hat S$</span>, the final estimate of test score.</li>
</ol>
<p>Is it a proper solution? Can we use it to compare different model architectures? And finally, is the estimate unbiased?</p>
Answer: <p>Yes, nested cross-validation will produce an unbiased estimate of the model building process. That is the point of it.</p>
<p>The whole point of this is that the inner cross-validation could be biased because you are performing a hyperparameter search on the same data you are pulling repeated validation sets from. This will likely be overly optimistic as the validation set leaks some information to the hyperparameter search process.</p>
<p>The typical way we counteract this is to reserve yet another set, the test set, to test on the tuned model trained on 'data_train_k'. This has drawbacks too though, because you have split your data with a randomization and so there could be some bias in the test set either way. And, you don't get bounds on the performance this way. So, if we nest the process, we can produce randomized test-sets over and over and now we can generate some unbiased bounds on our models. This is mostly for testing the whole process of building the model using your hyperparmater search technique and a particular model.</p>
<p>I think the architecture search needs to be part of the inner cross-validation as well. For example, if you are trying to decide between SVM vs MLP vs boosted trees, etc... then that is basically a hyperparameter as well. The outer test set needs to be completely naive to all processes. You don't want to re-run the whole nested cross-validation over and over, because now YOU are the one biasing the data by playing around with the architecture. You would now need yet <em>another</em> held out set to test final performance.</p>
<p>The final model you would use for production would of course then be trained once using all of the data and the best technique.</p>
<ul>
<li>Edit: I just wanted to edit this as my last statement might be misleading. The final model can be trained using all of the data via the same technique we applied in the inner loop. It is then ready for new data and we have an idea of how it would perform on this data.</li>
</ul>
|
https://datascience.stackexchange.com/questions/120428/does-double-cross-validation-make-sense
|
Question: <p>Does cross_val_score in scikit-learn split the data consistently or randomly? I noticed that cross_val_score lacks a random_state parameter, but the documentation mentions stratified k-fold cross-validation, which is implemented in the StratifiedKFold class that does have a random_state parameter for shuffling. So, how exactly does cross_val_score work? Does it split the data in a specific order or does it shuffle it? Furthermore, is the distribution of classes in each fold the same as the distribution in the original dataset? Lastly, which class or function in scikit-learn do you use for cross-validation?</p>
Answer: <p><code>cross_val_score</code> is a convenience function which relies on <code>KFold</code> or <code>StratifiedKFold</code> (see <a href="https://scikit-learn.org/stable/modules/cross_validation.html#cross-validation" rel="nofollow noreferrer">documentation</a>):</p>
<blockquote>
<p>When the cv argument is an integer, cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.</p>
</blockquote>
<p>This implies that by default <code>cross_val_score</code> won't split the data randomly, since by default <code>shuffle</code> is false for both <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html#sklearn.model_selection.KFold" rel="nofollow noreferrer"><code>KFold</code></a> and <code>StratifiedKFold</code>.</p>
<p>As per the documentation (see above), <code>StratifiedKFold</code> is used by <code>cross_val_score</code> if the classifier derives from <code>ClassifierMixin</code>. If so, the distribution of the classes will be strictly equivalent as the original distribution.</p>
<p>I tend to use <code>KFold</code> because it gives more control over what's being done.</p>
|
https://datascience.stackexchange.com/questions/121673/scikit-learn-cross-val-score-randomness
|
Question: <p>I have done a 10 fold Cross Validation on my data and have selected the best model from the results. With cross validation, I will have 10 models trained from different folds of the data. For the final model to use, should I take the average of the models or just fit a model for the entire training set?</p>
Answer: <p>Typically you would use the best model parameters and then re-run the model with the portion of the data set aside for training to come up with a new 'best' that you can run against your test set.</p>
|
https://datascience.stackexchange.com/questions/56108/best-practice-with-cross-validation
|
Question: <p>Let's say we have model M1 and model M2 that we want to compare. When we do 5-fold (say) cross validation, would the correct method to be to partition the data into F1, F2, F3, F4, and F5 and then run both models through those folds? Then would the way to assess if M2 outperforms M1 be to do a paired t-test?</p>
<p>I'm mostly thinking about a situation where I have the results of a cross-validation that someone else did and want to see if my model can beat their average of 80% accuracy. In that case, I would not have their exact folds or perhaps not even how many folds they used, so a paired t-test would not be possible. What would be the pitfalls of comparing to their metric or to their 5 metrics on the 5 folds when I don't know exactly how they allocated the observations into folds?</p>
Answer: <p>There seem to be a few elements of confusion here. I'll try to answer clearly, but would definitely appreciate input from others.</p>
<p><strong>1. What is cross-validation for?</strong></p>
<p><em>Cross-validation</em> is generally used as a mechanism for figuring out which of several models might be a better fit for data based on a <em>training set</em> before choosing a model to apply to the <em>test set</em>. This is commonly done when tuning hyperparameters (such as penalty factors in regularized regressions), and in other scenarios as well.</p>
<p>In such a case you <em>would</em> want to use the same folds for cross-validating each model, because you want to identify differences in performance attributable to the models themselves, and not due to effects of randomly partitioning observations into different folds. <strong>Importantly, cross-validation is part of the <em>model training</em> process, not final model evaluation.</strong></p>
<p>Cross-validation is <em>not</em> for finding the "best" performing model overall. Model performance is based on application to a held-out test set of observations. The idea is that the model performance will often be artificially high in the training data due to idiosyncrasies among the training data set which are not present in observations overall, and application to the test data suggests how the model might generalize to totally novel observations. Even if cross-validation results are discussed in a study, they are not the appropriate value to compare a model prepared independently and trained on different data.</p>
<p><strong>2. During cross-validation, how would one assess which putative model is "better"?</strong></p>
<p>This question can be a bit controversial, namely in that accuracy (such as of classification) is not a very strong method of identifying the best model during cross-validation. It will work with varying degrees of quality depending on what you're modelling. But better measures are varieties of <em>loss functions</em>, which could be mean squared error, binomial deviance, or many others (it's very situation dependent).</p>
<p>How you would compare the output of those loss functions is usually fairly straightforward-- you want minimum error, minimum deviance, etc. Performing a paired t-test isn't really appropriate. Such a test would tell you something about the distributions underlying your variables for data points that are connected in time (like measures of some variable before and after a treatment is applied) in the context of a specific null hypothesis and alternative hypothesis set. That sort of paired relationship doesn't apply to observations subjected to different models one-at-a-time, and in a mutually exclusive way.</p>
<p><strong>3. What should be done instead?</strong></p>
<p>As outlined above, model performance is assessed on novel data rather than training data. In model development that will be the test set, but it can just as well be application of the model to totally new data. If the models to be compared are similar in complexity, a proper loss function is still ideal. But in many situations classification accuracy is necessary (if that's what your boss is asking for, that may be what you have to provide).</p>
<p>In that case simpler counts of correct classification (9 out of 15 were correctly classified) are appropriate. Better still are measures of model sensitivity and specificity (the model's ability to identify true positives and true negatives, respectively, as in binomial classification) and positive/negative predictive value (how reliable any given classification suggested by the model is) can be very effective.</p>
<hr>
<p><strong>tl;dr:</strong> Cross-validation is the wrong stage to be comparing an already-trained model to a different model that is being trained, and t-tests are not informative in comparing cross-validations. Loss functions or classification accuracy are more appropriate (to varying degrees in varying situations) and should be based on data <em>not</em> used in training.</p>
|
https://datascience.stackexchange.com/questions/51703/cross-validation-for-model-comparison-use-the-same-folds
|
Question: <p>I found a question (Question 7) <a href="https://www.sanfoundry.com/data-science-questions-answers-cross-validation/" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>Question: For k cross-validation, larger k value implies more bias
<br> Options: True or False</p>
</blockquote>
<p>My answer is: <strong>True</strong>. <br>
<strong>Reason:</strong>
Larger K means more folds means smaller test set which means larger training set. As you increase training data you bring down variance which means increase bias.</p>
<p>So as K increases --> Training data size increases --> Variance reduces --> Bias increases
Hence answer is True</p>
<p><strong>But the website says answer is</strong> <strong>False</strong>. <br>
Can someone explain if my logic is wrong and why their answer is right?</p>
Answer: <p>Why should bias increase as the training set size increases?</p>
<p>My intuition is that as you increase K, your test sets get smaller, increasing the variance of your evaluation metric. At the same time, you're fitting your model to more and more similar training data (since the training set in each fold is approaching the full set), so you're more likely to overfit to the training data because you're fitting your candidate models on almost the entire training data set in each fold.</p>
|
https://datascience.stackexchange.com/questions/92902/cross-validation-and-bias-relation
|
Question: <p>I do not get why in <a href="https://datascience.stackexchange.com/questions/123130/for-cross-validation-should-i-use-training-set-or-whole-dataset">For cross validation should I use training set, or whole dataset?</a> the responses say that cross validation must be done exclusively on training set. Doesn't the methods (for example in scikit) make for each split an independent train-set procedure? Isn't that the whole point of CV?</p>
Answer: <p>Cross-validation can be used on two levels.</p>
<ol>
<li><p>When you want to evaluate an estimator <span class="math-container">$h$</span> by estimating its risk <span class="math-container">$\mathbb{E}[L(h(x),y)]$</span> based on some loss function <span class="math-container">$L$</span>, you need independent samples to compute the estimator <span class="math-container">$h$</span> and to compute the expectation. Then you can use cross-validation on all the data to get a better estimate of the risk than just using a single data split. Typically, this is done for a final analysis of a learning algorithm to publish its performance in a paper or a report.</p>
</li>
<li><p>In many cases learning algorithms also need to estimate the risk during their training process for hyper-parameter tuning (for example selecting the regularization parameter for a linear regression model), for which they can also use cross-validation. Then cross-validation is only applied to the training data as it is part of the training process.</p>
</li>
</ol>
<p>The other issue raised in the linked post do not seem to me specific to cross-validation only. If you conduct your research on the same data for years designing and tuning many algorithms on it, then you will likely overfit that data irrespective whether you use cross-validation or any other data splitting method.</p>
<p>Data leakage typically becomes an issue when the samples are not independent, which often happens for time series data. Then you might have to discard samples to avoid leakage. But this issue again applies to all data splitting methods, not just cross-validation.</p>
|
https://datascience.stackexchange.com/questions/128741/cross-validation
|
Question: <p>Context: I'm training an RNN with LSTM layers using the keras api. I have sequences of 20 timesteps, but just a binary response. For example: X=[[[1,2,3], [2,3,1]], [[4,1,2], [2,1,3]]], and y = [[1.0], [0.0]]. The binary variable y explains the action of the <strong>next</strong> timestep, because that is all I'm interested in, even though each vector in the sequence has an associated response to it. When training the model with one timestep ahead, I get specifications that look like the following.<a href="https://i.sstatic.net/ccBCo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ccBCo.png" alt="enter image description here"></a></p>
<p>Everything looks normal there. However, since I also want to predict two timesteps ahead, I train the same model, but cutoff the last vector in the sequence, but keeping the same response, thereby forcing to look ahead by two timesteps. After plotting the same curve, something strange happens:
<a href="https://i.sstatic.net/3hI1G.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3hI1G.png" alt="enter image description here"></a></p>
<p>A sharp vertical jump occurs around the cutoff of .43, in such a way that I've never seen before. When I test it with 3 timesteps ahead, the exact same thing happens, just at a different cutoff (around .2). What I curious about, is this common, and is it indicative of something greater? Why would such a drastic change in just the sensitivity occur?</p>
<p>I'm not sure if it's relevant, but this is the layout of the model:</p>
<pre><code>model = Sequential()
model.add(Masking(mask_value=0, input_shape=(seq_length, 66)))
model.add(LSTM(64, return_sequences=False, W_regularizer=regularizers.l2(.001)))
model.add(Dropout(.2))
model.add(Dense(1, activation='sigmoid'))
rms = RMSprop(lr=.001)
model.compile(loss='binary_crossentropy', optimizer=rms, metrics=['acc', 'fmeasure'])
</code></pre>
Answer:
|
https://datascience.stackexchange.com/questions/18174/what-might-explain-a-dramatic-vertical-jump-in-sensitivity
|
Question: <p>I'd like to get an intuition about how varying <em>k</em> impacts k-fold validation.
Is the following right?</p>
<p><strong>Average of the OOS MSEs should generally <em>decrease</em> with k</strong>
Because, a bigger "k" means the training sets are larger, so we have more data to fit the model (assuming we are using the "right" model).</p>
<p><strong>Variance of the OOS MSEs should generally <em>increase</em> with k.</strong>
A bigger "k" means having more validation sets. So we have have more individual MSEs to average out. Since the MSEs of many small folds will be more sparse than MSEs of few large folds, variance will be higher.</p>
<p><a href="https://i.sstatic.net/2I4Zf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2I4Zf.png" alt="enter image description here"></a></p>
Answer: <p><strong>Average of the OOS MSEs should generally <em>decrease</em> as k increases.</strong> This is right but the difference is much less then on your chart. Suppose we have a dataset where the error will halve if we increase the data 10 times (approximately true for the paper <a href="http://www.aclweb.org/anthology/P01-1005" rel="nofollow noreferrer">Scaling to Very Very Large Corpora for Natural Language Disambiguation</a>). Then the difference between 5-fold and 20-fold validation will be about 5% <code>(1/(2^log10(0.95/0.8))</code> not halving like on your graph. And the difference between 20-fold and infinity-fold will be only about 1.5% <code>(1/(2^log10(1/0.95))</code></p>
<p>For the chart you could use the formula: <code>Average OOS MSE = 1/(2^log10(1-1/k))*MSE_inf</code>. This will assume that you have MSE = MSE_inf at infinity. </p>
<p><strong>Variance of the OOS MSEs should generally <em>increase</em> as k increases.</strong> MSE is an average and according to the <a href="https://en.wikipedia.org/wiki/Central_limit_theorem" rel="nofollow noreferrer">Central Limit Theorem</a> (if squared errors (SE) are independent and identically distributed which, in my opinion, is supposed for most of the machine learning algorithms) variance should equal to Var(SE)/N, where N is the number of data points used to calculate MSE. So for 5-fold you will have variance Var(SE)/(Npop/5) Where Npop is the total number of points that you have. For the average MSE between all k-folds the variance will be the same and equal to Var(SE)/Npop. <strong>So the answer is</strong> that the variance of individual MSE numbers of each k-fold increases with k, but the variance of the final average MSE does not depend on the number of folds.</p>
<p>To calculate the variance of the final MSE based on MSE of folds:</p>
<pre><code>Var(MSE_final) = Mean(Var(MSE_folds))/k = Sum((MSE_folds - Mean(MSE_folds))^2)/k^2
</code></pre>
<p><strong>MSE change based on number of folds</strong>
<a href="https://i.sstatic.net/DxkLi.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DxkLi.png" alt="MSE"></a>
Here MSE at infinity is assumed 0.05.</p>
<p><strong>Variance of individual k-fold MSEs change based on number of folds</strong>
<a href="https://i.sstatic.net/KlAHQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KlAHQ.png" alt="Var_MSE"></a>
Here Var(squared error for one point) is assumed 10 and number of observations is 1000.</p>
|
https://datascience.stackexchange.com/questions/37150/k-fold-crossvalidation-how-do-mse-average-and-variance-vary-with-k
|
Question: <h3>Repeated K-Fold vs Group K-Fold</h3>
<p>As per my understanding from sklearn docs</p>
<p><strong>Repeated K-Fold:</strong></p>
<p>RepeatedKFold repeats K-Fold n times. It can be used when one requires to run KFold n times, producing different splits in each repetition.</p>
<p><strong>Repeated Stratified K-Fold cross validator:</strong></p>
<p>Repeats Stratified K-Fold n times with different randomization in each repetition.</p>
<p><strong>Group K-Fold:</strong></p>
<p>GroupKFold is a variation of k-fold which ensures that the same group is not represented in both testing and training sets.</p>
<blockquote>
<ul>
<li>Can somebody explain in-detail, When would one use Repeated K-Fold over Group k-fold? </li>
<li>What are the advantages/disadvantages of using Repeated K-Fold over Group k-fold?</li>
</ul>
</blockquote>
Answer: <p>Group k-fold is sufficiently specialized that the comparisons you ask for don't really make sense. "Repeated" really does just mean to remake the splits multiple times; you could easily make a "repeated group k-fold" splitter.</p>
<p>You use group k-fold when you have groups you don't want split across the training and test sets. For example, if your data includes multiple rows for each customer (but it still makes sense to train on individual transactions/rows), and your production use-case involves making predictions for <em>new</em> customers, then testing on rows from customers that also have rows in your training set may be optimistically biased.</p>
<p>You use repeated XYZ when the data and models have high variability and you want more performance datapoints with which to make statistically sound statements. (Likely this is when your dataset is small, in which case happily your model building should be faster so that you can afford the computational cost of repeating the cross-validation procedure multiple times.)</p>
<p><a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html</a><br>
esp. the image:<br>
<a href="https://i.sstatic.net/a0qtJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/a0qtJ.png" alt="sklearn docs visualization of group k-fold"></a><br>
(but now I'd like to see one with groups not lining up with classes like that...)</p>
|
https://datascience.stackexchange.com/questions/63901/cross-validation-repeated-k-fold-group-k-fold
|
Question: <p>It's my understanding that selecting for small models, i.e. having a multi-objective function where you're optimizing for both model accuracy and simplicity, automatically takes care of the danger of overfitting the data.</p>
<p>Do I have this right?</p>
<p>It would be very convenient for my use case to be able to skip lengthy cross-validation procedures.</p>
Answer: <p>There is no free beer in such matters so "automatically takes care of the danger of overfitting the data" is not true. When you optimize for a loss error function and also for simplicity the immediate question is how do you trade off simplicity on loss error. There is no answer to that, other than in very specific cases (but those cases are so constraint so they can't provide a generic answer).</p>
<p>This is the reason why many models which allows you to do this trade off will give you a parameter or more to use as knobs for this trade off. Examples are logistic regression with regularization, neural nets with dropouts, decision trees with max tree levels, boosting models with learning rates, and how many more. Even if the model does this trade off automatically, it does not mean it is the best trade off, mostly it is some trade off incorporated into the model structure and its assumptions.</p>
<p>The second aspect of your question is that you do not consider the whole scope of cross validation and of similar medthods in general. CV is used to assess the performance of different models, either if they have the same structure but with different parameters, either they are from different families. CV allows you to have a reliable hind regarding which will be the error of a model if used on similarly distributed new data. This is not covered by regularization at all.</p>
|
https://datascience.stackexchange.com/questions/92571/does-adding-a-model-complexity-penalty-to-the-loss-function-allow-you-to-skip-cr
|
Question: <p>I am new to machine learning, though I have a background in statistics. But I had a question about $k$-fold cross-validation. So I understand the basic idea that we divide the dataset into $k$ partitions and then train a model on $k-1$ partitions while testing on the $k$th partition that was left out. So we don't want to train the model over the entire dataset, but instead over just our $k-1$ partitions.</p>
<p>My question was how do we handle changes in the model parameters with each fold in the process. Another way of asking this question is how do we choose the model to test? So when you train on $k-1$ folds, in each iteration there will be a subtle change in the parameter estimates--namely the $\beta_{0...p}$s will change. So when we test the model against the testing partition, we are not testing the same model each time--because the parameter coefficients are different. </p>
<p>Given that the $\beta$s change for each fold, how do we choose which model to use? And once we choose a model, do we need to test only this model for the $k-fold$ cross-validation, for otherwise we are testing different models and then averaging their prediction error. </p>
<p>Any clarification would be appreciated. </p>
Answer: <p>There are two main (set of) things your model needs to learn from training: <strong>Parameters</strong> and <strong>Hyperparameters</strong>.</p>
<p>Parameters are those that can be inferred (learnt) from data. These are internal to the model and will be calculated in the training phase during. The hyperparameters however, cannot be learnt from data and need to be decided (make assumptions) before training. As you come from statistics, an example could be modelling a distribution from a set of samples. Parameters could be mean and std, and hyperparameter could be selecting a Normal distribution or a Beta distribution.</p>
<p>If you don't have hyperparameters (e.g. simple regression model), you only need to train the model and let the algorithm find the optimal weights (parameters) using the data. However, if you want to use let's say Support Vector Machines, then you need to provide some hyperparameters such as the cost, kernel, parameters of the kernel, and so on... before starting the training.</p>
<p>Cross Validation can be used to find the optimal hyperparameters. It is done by creating a grid of potential hyperparameter values and training each combination of them against the whole data, performing k trainings of k-1 portions (or <em>folds</em>) of data. For each specific combination of hyperparameters the model is then trained and evaluated k times, getting a number of predictions equal to the number of folds (k) for each hyperparameter combination. The combination that yields better results based on the specified metric, is considered the best option (final model).</p>
<p>Have a look at this nice <a href="https://machinelearningmastery.com/difference-between-a-parameter-and-a-hyperparameter/" rel="nofollow noreferrer">blog</a> for further clarification.</p>
<p>Cross validation procedure:
<a href="https://i.sstatic.net/epAqA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/epAqA.png" alt="enter image description here"></a></p>
|
https://datascience.stackexchange.com/questions/28420/k-fold-cross-validation-model-selection-or-variation-in-models-when-using-k-fol
|
Question: <p>I fully understand the data partition in a nested k-fold CV. But reading this:</p>
<blockquote>
<p>Within each outer fold, the best performing model was selected based on mean root mean squared error (RMSE) over the
inner folds. The model was then retrained on all training and validation data from the inner
folds and final generalization performance was evaluated on the held-out test data of the
outer fold. Repeating this process for each outer fold yielded 3 best-performing models, and
the mean test performance of these models is reported here...</p>
</blockquote>
<p>I have a question: after the inner loop is complete, they've retrained the best model on the whole inner dataset (which makes sense, and is permittable since the tuning process hasn't "seen" the outer, test dataset) but in this retraining, which model over training epochs is selected now?</p>
<p>I believe there are two options: You'd treat the new test data as validation data and pick the best validation accuracy epoch during training,</p>
<p>or you can pick the best training accuracy epoch during training and test it independently on the test data.</p>
<p>Which one is it?</p>
Answer: <blockquote>
<p>The model was then retrained on all training and validation data from the inner folds</p>
</blockquote>
<p>My understanding is that the inner fold already contains some training and also validation data, so retraining is done with the latter as validation data.</p>
<p>There is another reason not to use the new outer fold test data as validation: this causes a bias in the obtained performance, unless there is some other fresh test data on which the model is evaluated later.</p>
|
https://datascience.stackexchange.com/questions/123711/trying-to-understand-nested-k-fold-cv-in-a-paper
|
Question: <p>My course notes list two reasons why cross-validation has a pessimistic bias. The first one is that the accuracy is measured for models that are trained on less data, which I understand. However, the second reason I don't understand. Supposedly, when we do cross validation and divide our data D into training sets D_i and test sets T_i, then the D_i and T_i are not independent (and even complementary) given D.</p>
<p>However, I don't see why this is different from the situation where we use a fixed testset: if we have a training set D and test set T, than T and D are also not independent given the union of D and T. In this case there is no bias, so I would expect there to be no bias for cross-validation either (apart from the fact that the model is trained on less data). Of course, since the different models that we train for cross validation use overlapping data, I would expect their accuracy to be correlated, which could lead to a higher variance, but I don't see how this could give a bias.</p>
Answer:
|
https://datascience.stackexchange.com/questions/84754/why-does-cross-validation-have-a-pessimistic-bias
|
Question: <p>I am trying to train and validate my datasets which contains 17 datasets. I have divided them as 15 for training and 2 for validation.
In the process, I train on 15 datasets and use the generated model to predict the results on the remaining 2 datasets. This process is called leave out validation in my understanding.
Irrespective of the classifier I use (SVM, optimizable SVM, knn, optimizable KNN), I always get a very high training accuracy closer to 90-100%.
The validation accuracy is comparatively poorer closer to 50-60 %.
The datasets in the validation set will be a part of training in some runs. In this case, I can not understand if they are doing so good in the training why the validation results are so bad.?</p>
Answer: <p>[edited after clarification by OP]</p>
<blockquote>
<p>I can not understand if they are doing so good in the training why the validation results are so bad.?</p>
</blockquote>
<p>This is certainly due to major differences between the datasets. Supervised learning relies on the assumption that both the training set and the test set are samples from the same population (i.e. they follow the same distribution). In your case the model assumes that the 15 datasets used as training data are a representative sample of "the" data distribution. If the two datasets used as test set have very different distributions, then what the model learned is simply not applicable to the test set.</p>
<p>I think this is a form of <a href="https://en.wikipedia.org/wiki/Overfitting" rel="nofollow noreferrer">overfitting</a>: the model learns some details of the instances instead of the true patterns which matter for the target variable. These details actually happen in the training set, so the performance is good on it. But they don't happen (at least not in the same way) in the validation set, so the true performance is poor.</p>
<p>Note: your evaluation setting is similar to leave one out (LOO) cross-validation, but this is not LOO because LOO means leaving a single <em>instance</em> as test set.</p>
|
https://datascience.stackexchange.com/questions/101754/leave-one-pair-out-cross-validation
|
Question: <p>I'm trying to do nested CV for my multivariate time series but I'm really confused how to do it. I have 7 Time series which are the inputs of my CNN model and one time series as target.Always when I read about it I found they talk about univariate.Any advices</p>
Answer:
|
https://datascience.stackexchange.com/questions/78122/how-can-i-do-nested-cross-validation-for-multivariate-time-series-forecsting
|
Question: <p>Let's say I have 5 models cross-validated via leave-one-out strategy. I have the predictions and scores of each model.</p>
<p>Now, it's time to calculate the average for the set of 5 models - am I supposed to:</p>
<ul>
<li>add up the 5 losses and divide them by 5?</li>
<li>Or average their probabilities for each prediction and use the average probability to calculate new metrics like an ensemble/ forest?</li>
</ul>
Answer: <p>A standard way to provide the performance of each model would be:</p>
<ul>
<li><p>providing, for each split, the value of the chosen metric (accuracy, roc_auc, etc) on the train and test sets (on your case, your one-out sample), something like this (in this case with 2 models):
<a href="https://i.sstatic.net/jS2ks.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jS2ks.png" alt="enter image description here" /></a></p>
</li>
<li><p>as a final model performance (for each one of the 5 models), a mean metric value together with its standard deviation for the test sets is a way to inform about the model quality and its robustness, something like (preferably for the test set):</p>
</li>
</ul>
<p><a href="https://i.sstatic.net/Zxjst.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Zxjst.png" alt="enter image description here" /></a></p>
<p>You have more detail on how to automatically get this done via <a href="https://scikit-learn.org/stable/modules/classes.html#module-sklearn.model_selection" rel="nofollow noreferrer">scikit-learn</a>, and in <a href="https://datascience.stackexchange.com/questions/86912/k-fold-cross-validation-with-validation-and-test-set/86913#86913">this answer</a> and <a href="https://datascience.stackexchange.com/questions/84971/compare-cross-validation-and-test-set-results/84973#84973">this one</a>.</p>
<p>By the way, consider using another strategy as stratified k-fold, in case you have a lot of samples, as leave-one-out would be very costly.</p>
|
https://datascience.stackexchange.com/questions/87290/cross-validated-average-metrics-mean-or-ensembling-probabilities
|
Question: <p>I am all new with ML. I try to understand what is Kfold and cross_val_score.<br />
I made this model:</p>
<pre><code>RandomForestRegressor(max_depth=17,n_estimators=93,criterion='mse')
modelfinal.fit(xtrain1, ytrain1)
mrse_test = np.sqrt(mean_squared_error(y_pred=modelfinal.predict(xtest1), y_true=ytest1))
</code></pre>
<p>It gave me:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Train/test</th>
<th>R2</th>
<th>mae</th>
<th>mrse</th>
</tr>
</thead>
<tbody>
<tr>
<td>Train</td>
<td>0.94</td>
<td>13.52</td>
<td>22.07</td>
</tr>
<tr>
<td>Test</td>
<td>0.605</td>
<td>34.57</td>
<td>56.592</td>
</tr>
</tbody>
</table>
</div>
<p>Because on the train, it gave me 0.9 as R2 and only 0.6 on test.
<em>I have been told I should use Kfold cv to see if I have over overfitting or not.
But I just can't understand how it will help me, and what I did is right or not.</em>
This is what I did:</p>
<pre><code>cv=ShuffleSplit(5,test_size=0.2)
score=cross_val_score(modelfinal, X, Y, cv=cv)
</code></pre>
<p>This is what I get:</p>
<pre><code>array([0.59618812, 0.57799759, 0.55214982, 0.63904499, 0.65027832])
</code></pre>
<p>What can I conclude from this?</p>
Answer: <p>Overfitting is visible when the performance on the training set is much higher than the test set, so you clearly had overfitting with your first experiment already.</p>
<p>Cross-validation is not a way to see overfitting by itself, it's a way to obtain a more reliable performance value by using several splits (removes chance factor) and using an overall larger test set (the full data).</p>
<p>One thing I notice in your experiment is that the <code>max_depth</code> parameter is set to 17 which is very high, especially in case your training set is not too large. This means that you're allowing the model to create very big and complex trees, so there is more chance that it would represent small patterns which happen by chance in the data. Try reducing this parameter value, hopefully this will avoid or at least decrease the overfitting. If it's not enough there might be some work to do at the level of features: too many features and/or not enough instances can cause overfitting as well.</p>
|
https://datascience.stackexchange.com/questions/87709/kfold-or-cross-val-score
|
Question: <p>I asked a data science question regarding how to decide on the best variation of a split test on the Statistics section of StackExchange. I hope I will have better luck here. The question is basically, "Why is mean revenue per user the best metric to make your decision on in a split test?"</p>
<p>The original question is here: <a href="https://stats.stackexchange.com/questions/107599/better-estimator-of-expected-sum-than-mean">https://stats.stackexchange.com/questions/107599/better-estimator-of-expected-sum-than-mean</a></p>
<p>Since it was not well received/understood I simplified the problem to a discrete set of purchases and phrased it as a classical probability problem. That question is here: <a href="https://stats.stackexchange.com/questions/107848/drawing-numbered-balls-from-an-urn">https://stats.stackexchange.com/questions/107848/drawing-numbered-balls-from-an-urn</a></p>
<p>The mean may be the best metric for such a decision but I am not convinced. We often have a lot of prior information so a Bayesian method would likely improve our estimates. I realize that this is a difficult question but Data Scientists are doing such split tests everyday. </p>
Answer: <p>If you've got prior information then you should certainly not use simple mean in a split test. I assume you're trying to just predict which group will produce the greatest amount of revenue overall, by trying to emulate the underlying distribution.</p>
<p>Firstly, it's worth noting that any metrics you choose will actually reduce to mean in a pretty trivial way. Eventually mean will necessarily work out, though using a standard bayesian method to estimate the mean is probably your best bet.</p>
<p>If you've got a prior then using a standard bayesian approach to update the prior on your mean revenue is probably the best way to do it. Basically, just take the individual results you get and update a multinomial distribution representing your prior in each case.</p>
<p>If you want some more full background on multinomial distributions as bayesian priors are pretty well, <a href="http://research.microsoft.com/en-us/um/people/minka/papers/minka-multinomial.pdf">this</a> Microsoft paper does a pretty good job of outlining it. In general, I wouldn't care so much about the fact that your distribution is technically discrete, as a multinomial distribution will effectively interpolate across your solution space, giving you a continuous distribution that is a very good approximation of your discrete space.</p>
|
https://datascience.stackexchange.com/questions/748/why-use-mean-revenue-in-a-split-test
|
Question: <p>As I understand it one can use cross validation to help find the optimal pruning of a classification or regression tree, for example, implemented here in <a href="http://au.mathworks.com/help/stats/classificationtree.cvloss.html#bunpajd-1" rel="noreferrer">Matlab</a>. </p>
<p>I do not understand the following about this process. Since each cross validation fold has random data, it may be that the trees fit on each data set may be different and have differing depths. How can one find the best pruning level over all such trees then?</p>
Answer: <p>I don't know how this is implemented in matlab. I know that some packages use cross validation to decide whether to grow the tree or not. Quite simply, they decide whether to grow based on that evaluation.</p>
<p>(Notice what a lot of packages call pruning is: during training, they mark branches with some score criterium and then remove if the user wants afterwards.)</p>
<p>Personally, I use sklearn which does not have this feature. So, I just do a grid search for several values of <code>max_depth</code> and use whatever maximizes accuracy or whatever score I want.</p>
|
https://datascience.stackexchange.com/questions/8598/how-is-cross-validation-used-to-prune-a-decision-tree
|
Question: <p>Is there a way to directly calculate an approximate quad weighted kappa measure from an OOB estimate, obtained from a gradient boosting model with subsampling without going through cross validation?</p>
Answer:
|
https://datascience.stackexchange.com/questions/9923/convert-out-of-bag-oob-estimate-to-quad-weighted-kappa-score
|
Question: <p><strong>Background:</strong>
I am trying to use Orange as to classify if a patient has TB based on their coughing sounds.</p>
<p>In the dataset, there are say 100 patients and for each patient we have 10 coughs. For each cough, we have a full feature vector (170 features). </p>
<p>Giving Orange this dataset and training various learning algorithms is fairly straightforward, but the issue that I have is that Orange will consider each feature vector to be independent of another feature vector, which means it will consider every cough of each patient to be independent, and they aren't. </p>
<p>So my question is: Is there a way to tell orange that all 10 coughs of a patient belong to that patient, and when performing leave-one-out or cross validation methods, all the coughs from each patient should be excluded in each fold? </p>
Answer: <p>This is not Orange-specific, but IIUC, you could preprocess your data (e.g. in Python or <a href="https://www.libreoffice.org/discover/calc/" rel="nofollow">Excel</a>) to have each of the 10 coughs pertaining to a patient on the same patients line. Thus you would have: 100 rows of patients with each row (10*170 + other patient data) attributes wide.</p>
|
https://datascience.stackexchange.com/questions/10824/is-it-possible-to-create-feature-groups-in-orange
|
Question: <p>I have a regression problem and I am in doubt about how I can calculate RMSE in my life-cycle.</p>
<p>I deal with time-series and for every prediction, I want to look N points in the future. It is apparent how to calculate RMSE for a single iteration. My question is how to calculate RMSE for N predictions of N points to get a meaningful prediction performance metric.</p>
<p>I guess, I can average RMSE of all iterations though as I said I am not sure at all if this would reflect actual performance.</p>
Answer: <p>The natural choice would be the total squared error across the N predicted values, averaged across all examples. This is the simple extension of mean squared error from the univariate case. If you're using multivariate linear regression, this is in fact what you want to optimize in order to get the maximum likelihood estimate of the parameters as well.</p>
|
https://datascience.stackexchange.com/questions/13411/cross-validation-strategy
|
Question: <p>What could be the possible reasons for a significant difference in cross validation and testing f1_scores? I am performing 3 fold Stratified cross validation and the testing f1_score is almost 0.15 less than cross validation score. How can I come up with a more effective cross validation strategy so that the two scores are closer?</p>
Answer: <p>Significant differences between the calculated classification performance in cross-validation and in the final test set appear obviously, when the model is overfitted. </p>
<p>A good indicator for bad (i.e., overfitted) models is a high variance in the F1-results of single iterations in the cross-validation. </p>
<p><strong>Possible strategies to get a better estimation of the model performance would be:</strong></p>
<ul>
<li>useing more folds (e.g., 10-fold cross-validation, or leave-one-out cross-validation)</li>
<li>considering simpler models (e.g., less variables, more general parameters)</li>
<li>considering other machine learning algorithms</li>
</ul>
|
https://datascience.stackexchange.com/questions/13753/significant-difference-in-testing-vs-cross-validation-accuracy
|
Question: <p>I have written a function for 10 fold crossvalidation that I want to use for different models, e.g PPR, MARS. However, I get an error when running it and I cannot figure out why it does not work? My CV function:</p>
<pre><code> cv10 <- function(reg.fn, formula, dataset, ...)
{
set.seed(201)
### Number of observations
nrow <- nrow(dataset)
### Create a permutation of the observations indices
Ind <- sample.int(nrow,nrow, replace = FALSE)
### Compute the size of each of the 10 folds
M <- nrow / 10 # 'fold size'
### Initialize the score
score <- 0
### The first fold will then contain the observations which correspond to..
### ..the indices of the first M elements of Ind.
for(i in 1:10){
beg <- i*M
end <- (i+1)*M
### Data to train the model
data.train <- dataset[Ind[-beg:-end],]
### Data to test the model
data.fold <- dataset[Ind[beg:end],]
### Fit the model
model <- reg.fn(formula,data=data.train,...)
predicted.y <- predict(model,data.fold)
### Update the CV-score
score <- sum((predicted.y - data.fold[,1])^2) / M
}
return(score/10)
}
</code></pre>
<p>Testing using ppr:</p>
<pre><code> cv.scores <- numeric(10)
### Some code
for(i in 1:10){
score <- cv10(reg.fn = ppr, formula = y~.,
dataset = data, nterms=i)
cv.scores[i] <- scores
}
cv.scores
</code></pre>
<p>The traceback:</p>
<pre><code>> Error in matrix(NA, length(keep), object$q, dimnames = list(rn,
> object$ynames)) :
> length of 'dimnames' [1] not equal to array extent
> 4.
> matrix(NA, length(keep), object$q, dimnames = list(rn, object$ynames))
> 3.
> predict.ppr(model, data.fold)
> 2.
> predict(model, data.fold)
> 1.
> cv10(reg.fn = ppr, formula = y ~ ., dataset = data, nterms = i)
</code></pre>
<p>The data I am using:</p>
<pre><code> structure(list(y = c(23.0551546516262, 27.8893494373006, 3.32468370559938,
-13.5852336127512, -5.14668013186906, -0.489523212484223, -14.328750654513,
-4.26428395686341, -2.75486620989581, 17.3107345018601, 25.6193450849393,
0.605103858286016, -1.30909806542865, 2.03575942172917, -19.1193524499977,
-1.46508279385589, 2.65778970954973, 14.8513018374104, -2.87449028138997,
1.37368992108124, -1.43518738939116, 0.0199676357940499, -1.549025998582,
-4.06263285631006, -9.15130335901099, -2.62794216480131, -1.68473200963303,
3.15144283445608, 7.78027589015824, 9.09732626327383), x1 = c(0.286060694657523,
-0.344546030966432, 0.325763726232689, -1.69658096808073, -1.2854825202758,
-0.0750318862014798, 0.266937353823139, 0.0559340444850217, -2.30403430891787,
0.189004139305415, 0.693296170158882, 0.223809355083932, 0.398456942903131,
1.01347438447768, -0.64785307166209, 0.648452713333917, 0.207342703528518,
0.0643901392726141, 0.669380920067964, -0.374254446133507, -0.244000842201787,
-0.988253138922366, 1.24206047974719, -1.68266602919039, 1.44289062580162,
-0.465439746975312, 0.693661499094998, -0.0877255722586039, -0.955080382553146,
0.170100884691593), x2 = c(-0.343601401483176, -0.924078839603673,
0.973710320640175, 0.0267187344544633, -1.36283892301834, 0.105184057636645,
-0.644019900369909, 0.960031901250783, 0.147336523178527, 0.339467057535232,
-0.192287076626924, 0.0722969316029643, 0.389789911800799, -0.328247051156339,
-0.090450711707476, 0.716681577815978, 0.0626860575507786, -0.69236622624416,
0.584444051353438, -0.0911664147267412, -0.315213328094698, -0.0806856079787168,
0.484583750517842, -0.120406402869962, 0.596077475841207, -0.36353784662963,
-0.780093462571257, 0.324679908484668, 0.508548510215705, -0.193595813912055
), x3 = c(0.982327855388361, 0.624091435911063, 0.621531522270016,
-0.902870741076395, 0.931325903563023, -1.05264178470207, 0.307132555544596,
0.275469955530981, 2.78596687577565, -0.590390951909848, -0.0257046477898407,
-0.122008374353289, 0.455026913225061, -0.607514744574133, 0.595817459312108,
1.48223488775224, 0.636854208609479, 0.201054337281812, -0.716437866742046,
-2.30960460962945, -1.11690418809942, 0.296611889529358, 0.992033628272787,
-0.769290105905667, -1.4112664763812, 0.972758797977034, 0.680563892580633,
0.0312007101558726, 2.40109797772769, 0.27149586035907), x4 = c(2.87744884192944,
2.97037391737103, 2.04590974515304, -2.09065303439274, -0.886272139381617,
0.258417838253081, -2.48789734393358, -1.14431498106569, 1.52785618370399,
2.43856811150908, 2.88160788919777, 0.143826744519174, -1.32458955561742,
0.850324050989002, -2.63397432630882, -0.270683331415057, 1.85416122945026,
2.19268380571157, -1.33175755385309, 1.08762756781653, 0.7014160878025,
0.907778979744762, -1.3183526317589, 0.718872689176351, -2.21834870846942,
-0.750489700119942, -0.889076801016927, 1.39292777515948, 2.34955989941955,
2.1975970286876), x5 = c(1.48984236368162, 0.869139640762428,
0.748845036625717, 0.351786000608901, -1.47779050566991, -2.3154451409239,
2.20221698212952, 0.414262887380592, 0.244955910040375, 0.429121363729595,
-0.317306195296495, -1.38016320237183, 0.694020488858179, 0.305431051706151,
-0.398558943204744, -1.00163421976715, 1.29024064725421, -0.770948417017754,
0.741664981312622, 0.169399870781162, -1.35676745536567, 0.471865193264912,
0.960859048309877, 1.46760491067668, 1.4378809852526, 0.0349201858899876,
-1.42177690061078, -1.43127605517511, -0.101638629745238, 1.49972397311187
)), .Names = c("y", "x1", "x2", "x3", "x4", "x5"), row.names = c(NA,
30L), class = "data.frame")
</code></pre>
Answer: <p>Because your data has 30 rows and your loop is from 1 to 10 so when it gets to <code>i=10</code> then <code>end <- (i+1)*M</code> which is 11 * 3 which is 33 and then you do <code>Ind[beg:end]</code> but <code>Ind</code> is only 30 long so you get:</p>
<pre><code>[1] 21 NA NA NA
</code></pre>
<p>and then its NA NA NA NA hey hey goodbye.</p>
<p>You should try basic debugging techniques before posting here. Print <code>i</code> in the loop to see where it fails. Print intermediate values to check they are as expected. Step through code using RStudio's debugger if you are into that.</p>
|
https://datascience.stackexchange.com/questions/22247/r-function-for-10-fold-crossvalidation
|
Question: <p>I have done 10-Fold CV on my data and I have selected my model complexity from the result. Now for my best complexity, I will be having 10 different models. Should I take the average of these models for my testing or should I just fit a model of our selected complexity on our CV data and then test?</p>
Answer: <p>You re-train the model based on your best complexity (or parameters) on the complete training data. Then you can test the model on un-touched test dataset and report your error measure.</p>
|
https://datascience.stackexchange.com/questions/23277/cross-validation-model-selection
|
Question: <p>When K-fold validation should be used and how to decide the value of the K.
I see most of the text books suggesting implementation of algorithms using 2/3 of data as train and 1/3 of data as test</p>
Answer: <p>The main criterion is that you need enough data in your training set to get a good model fit - which is both a function of the data quantity and the model complexity.</p>
<p>When you don't have much training data, you want as much data in your training set as possible - in this case, you can do "leave one out" cross-validation. This is like k-fold, except it's N-fold, where N is the number of observations you have. This means you hold one observation out, build a model using everything else, validate using that one sample, and repeat N times.</p>
<p>When you have more data with a simple model, you can use a much more loose validation strategy. For example, if you have a million records and are doing linear regression with one predictor, you can get away with using a few thousand samples to build your model, since you'll get really good parameter estimates from thousands of samples (or fewer).</p>
<p>Those are the extremes. The suggestions you've seen live somewhere in-between. When you pick high K, you have to build lots of models (this takes time), but each model is built with more data (good for complex models). When you pick low K, you have to build fewer models, but each model is built with less data.</p>
<p>Personally, I pick a low value for K when I'm doing model exploration, but a higher value when I'm ready for validation of a good candidate model. Actually, in this case you should have three sets - a training set, a validation set (that you use to find a good set of parameters), and a second validation set that you've held out the ENTIRE time (since, in a way, the other validation sets are helping you 'train' the model parameters).</p>
|
https://datascience.stackexchange.com/questions/29607/how-to-decide-to-use-k-fold-validation-or-not
|
Question: <p>Say I've divided the data into 3 parts: training, validation and test. I know for example, that in Neural Networks, the number of hidden layers is a hyper parameter. Why can't I train numerous NN architectures in the training set and then test their accuracy in the test set; thereby allowing me to choose one final model? What is the purpose of the validation set in this instance?</p>
Answer: <p>I wouldn't say you can not tune the hyper-parameters in the trainig dataset, but the purpose of doing so is different than in the validation set.</p>
<p>In general, what it is intended with a ML algorithm is how to optimally classify or perform regression given some training data. Once the model is trained, it will be used with new data to obtain predictions, thus:</p>
<ol>
<li>We need some training data. With this dataset, the model will look for the optimal weights and biases that minimizes the selected loss function.</li>
<li>We need some upper bound to our performance metric: for example, we can decide that our model has to perform like a human, which has showed an average metric of 95% for some specific task. The upper bound can be the best score in a certan benchmark, etc.</li>
<li>We start training the model on the <strong>training</strong> data and we evaluate its metric, lets take the accuracy. If the accuracy is too low, we can tune the hyper-paramters until the accuracy increases in the training data (no evaluation dataset is used here). The difference between our model's accuracy and the upper bound is taken as the <strong>bias</strong> of the model (this bias has not to be confused with the biases of the neurons). So, the accuracy on the training data gives us the bias of our model.</li>
<li>Once we decided our bias is reasonable (optimally 0) arises the question of how the model will perform when it is fed with data that has not be used for training (the real application). The difference between the accuracy on this unseen data and the accuracy on the training data is the <strong>variance</strong> of the model. This unseen data is the <strong>validation set</strong> and give us an idea of how the model generalizes to new data. If the variance is high, then the model poorly generalizes to new data. Then, we perform hyper-paramater tunning and evaluating the accuracy on the validation data until the variance is low enough, trying to not worsening the bias (variance-bias trade-off).</li>
</ol>
<p>Example: desired accuracy = 95%. Training accuracy = 93%. Validation accuracy = 82% -> Bias = 2%, Variance = 11%</p>
<p>Summarizing:</p>
<ul>
<li>Tunning in the training data = decreasing bias</li>
<li>Tunning in the validation data = decreasing variance</li>
</ul>
<p>What's more unclear is the role of the test dataset. I usually use it when I decided that the model will be no longer changed and I need the final metric that describes the model. The test set can also be used to have an idea about how the model performs with data which have not be intended to work with. In general, the test set gives the power of the model for the inference task.</p>
|
https://datascience.stackexchange.com/questions/31662/why-cant-i-choose-my-hyper-parameter-in-the-training-set
|
Question: <p>What is the correct procedure for using a validation set to reduce overfitting? </p>
<p>Say I split the data 80:10:10 (training: validation:test). I train on the training set then get 90% accuracy. I apply this model to the validation set then get 20%. What do I do then? </p>
<p>How can the validation set be used to reduce overfitting especially with reference to Naïve Bayes?</p>
Answer: <p>It is not much about the algorithm you use. It is about the fact that you learned so much details from your training set so just tune the parameter inside a loop in which training and validation errors are calculated each time. In NB case, you do not have many parameters in that sense. Probably the features can be inspected instead of parameter. Then see the famous point at which the validation error is the minimum.</p>
<p>Do not use fixed splits. For each calculation in loop do <span class="math-container">$n$</span> times splitting + evaluation and take the mean and std of errors. Gives you better impression about the stability of the results and effectiveness of your algorithm.</p>
|
https://datascience.stackexchange.com/questions/40860/how-can-one-use-a-validation-set-to-reduce-overfitting-naive-bayes
|
Question: <p>Say we have N of labeled data, and we need to take some part for the <code>cross validation</code> (we will skip <code>test</code> part for this case). We chose, 0.6 part for the training and 0.4 for validation. </p>
<p>After training neural Network with <code>early stop</code>, we have found 8 epochs, as optimal to stop, and have received good enough results. </p>
<p>Q. In case, we have very limited N training samples. May we use all samples in new model training, and just stop it's training after discovered epochs? Without separating it to <code>train</code> and <code>cross validation</code>, and testing it, at all (or even, change rate of separating, to 0.9 train, 0.1 cross validation). </p>
<p>Maybe there is known technologies for such cases? Thanks. </p>
Answer: <p>Due to stochastic nature of NN training, the best epoch may vary upon each restart. In other words, at epoch 8, each of (the best, under-fitted, over-fitted) cases may happen. However, if you train multiple times and the best model is consistently found at (or around) 8th epoch, it is safe to say 8th epoch gives the best model away from under- or over-fitting, thus definitely validation set can be added to training set to improve the performance.</p>
<p>A more solid approach would be to plot the effect of training size (10% up to 90%) on the best epoch and the validation error. This means producing two plots (training size, the best epoch) and (training size, validation error), where each point is an average over multiple restarts. This way you can better find (1) the best epoch, and (2) the degree to which the added validation set will going to boost the performance on unseen test data, i.e. extrapolating the validation error for training size 100%. </p>
<p>It is possible that performance goes flat after for example 70% of training set, implying that adding the validation set has no gain.</p>
|
https://datascience.stackexchange.com/questions/46700/change-rate-of-cross-validation-data-after-training
|
Question: <p>I have a methodology question: are hold-out and CV generalization-optimization techniques mutually exclusive? It gets really confusing to me at times, because in the most recent project I have been doing something as follows:</p>
<ul>
<li>I have split the dataset into TRAIN and TEST sets (with stratified distribution)</li>
<li>I have applied gridsearchCV on the TRAIN set with cv = 10, so effectively the model was splitting TRAIN set into TRAIN' and VALIDATION sets at each fold</li>
<li>I have used the optimized trained model with the TEST set, and ended up with results 0.97 (TRAIN set) vs 0.68 (TEST set).</li>
</ul>
<p>Normally, when I see results like that my immediate reaction would be to assume that I am overfitting to the TRAIN set, and that the model does not generalize well enough. However, I have already used CV with the TRAIN set to make sure I was tuning the model to generalize as well as possible. I do not have any immediate tools (nor I should touch the already trained model) to improve this score now, since as I understand Hold-out technique, it just gives me the final score of how my model performs on previously unseen data.</p>
<p>At the same time, it feels kind of strange, since with using both CV and Hold-out, I am guaranteed to get some outliers in the hold-out set (TEST in my text above), which will fail.</p>
<p>Any suggestions or ideas?</p>
Answer: <p>You are correct in the sense that when tuning your model via. grid search you are technically not leaking any data. But, recall that tuning your model (via. a specific procedure such as grid search) is one of only many steps you probably took in fitting your model pipeline. In particular, areas such as pre-processing, feature engineering, imputation, model tuning, data aggregations, etc. The point of the test set is to capture the entire model building process and not just the process of model tuning.</p>
<p>Furthermore, it is highly known that validation scores reported during model tuning tend to be optimistically biased (and this bias tends to be worse with smaller datasets). This is because the probability of finding a set of hyper parameters that coincidentally minimizes the error for the validation set but not to the overall population (i.e., overfitting to the validation set) becomes higher the finer your grid is. Imagine theoretically tuning your model to one million different hyper parameter combinations. The probability of selecting a bogus set of hyper parameters (i.e. that are only optimal for the validation set) is now quite large due to the sheer number of possible candidates you have elected to try.</p>
<p>With a test set, this still won't prevent overfitting to a validation set. However, it will allow you to detect the problem and give you the true unbiased measure of model performance.</p>
<blockquote>
<p>At the same time, it feels kind of strange, since with using both CV and Hold-out, I am guaranteed to get some outliers in the hold-out set (TEST in my text above), which will fail.</p>
</blockquote>
<p>Indeed, which is a major drawback of cross validation and data splitting especially for smaller datasets (with a lot of outliers/noise). Basically, the performance measure you observe tends to be highly variable with how you split the data in the first place (that is, the seed you choose when splitting your data can lead to large changes in estimated model performance depending on where your outliers fall). The solution is unfortunately, not very glamorous and time consuming. In order to gain more certainty in our estimate, we need more than just a single estimate of model performance. Thus, simply repeat the entire model building process again with a different data partition (a different test set). Repeat this however many times, and average over all repeats. Possibly, form a confidence interval that allows you to see for yourself how variable your model's performance is.</p>
<p>I will also note that there are other ways to get around this problem, such as "optimism adjusted bootstrap", but recent issues have arisen with this method which have potentially shown that for high dimensional data this method does not do well, despite being more efficient than cross validation. Since high dimensional data is the norm these days, I have my doubts but perhaps it may be of use to you.</p>
|
https://datascience.stackexchange.com/questions/51984/applying-hold-out-and-cv-technique
|
Question: <p>I'm trying to replicate result of a paper. The paper is a U-net for De-noising of some images. So basically I have a simple U-net that I give noisy data as input and have denoised data as the wanted output (use l2/MSE loss) . So, in the paper and generally in most papers like this (deep learning applied to medical imaging), they say they run the model for something like 300 epochs or they say they run it like ~50 hours. My question is that aren't they supposed to put call backs for the validation loss, so once the validation loss stops improving they stop the training, otherwise the model will overfit? Also does the number of batches in an epoch matter. If because of memory constraints I use 2 batch sizes per epoch, would it be a bad practice?</p>
Answer: <p>Using validation loss to determine when to stop iterating is a good strategy when you have a lot of labeled training data. However, in medical contexts, it's often the case that labeled data is expensive and/or difficult to come by. You mention that you only have 1000 samples -- this is a pretty small amount of data to be training a deep net with! Setting aside 100 or 200 images to form a validation set will probably hurt the model. You can use a validation set to get an estimate of how many epochs you should train for, and then train on the whole dataset for that many epochs.</p>
<p>In regards to your batch size query: I would recommend working with smaller batch sizes of around 32-128 images. In my experience, the networks converge more quickly when using smaller batch sizes.</p>
|
https://datascience.stackexchange.com/questions/55093/training-deep-learning-and-validation-loss
|
Question: <p>Currently, I have trained my model through 5-fold cross validation with very small amount of the sample (n=100).</p>
<p>I used whole data set to train and got quite low performance in terms of accuracy, which is bit higher than 70%.</p>
<p>However, if I put my data which was used for training back to trained model to validate, it gives me higher accuracy (80%).</p>
<p>So, my question is it okay to say that I have verified my trained model using training set and got 80 of accuracy? or should I have to stick with 70 % of accuracy that I received from 5-fold cross validation?</p>
Answer: <p>Scoring your model using the training data is not a best practice. The reason is that you have already used this data to develop the "guess" at an accurate model.</p>
<p>This is akin to saying - 'Pick a random number between 1 and 10 (20 times)', here's a list of the last 10 numbers I picked to get you started. You pick 20 new numbers and come up with 5 correct (25%). What you are suggesting is that instead of reporting the 25% accuracy, that you would throw the first 10 back into the mix and report a 50% accuracy because now you've gotten 15 out of 30 right.</p>
<p>So there are two different things here. The MSE of your initial model against the data you gave it - provides you and understanding of how well the model demonstrates history. While the MSE (or other error metric) of the 'test' data shows how well you can predict the future.</p>
|
https://datascience.stackexchange.com/questions/56109/is-it-okay-to-use-training-data-for-validifying-the-trained-model
|
Question: <p>I'm trying to run cross validation with mean squared log error with sklearn and getting the following error message:</p>
<pre class="lang-py prettyprint-override"><code>ValueError: Mean Squared Logarithmic Error cannot be used when targets contain negative values.
</code></pre>
<p>This would suggest that I have negative values in my 1d array y. However, I have tried about 10 different ways of checking, including importing into excel and I can see no negative values in there. </p>
<pre class="lang-py prettyprint-override"><code>from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_log_error
import pandas as pd
import numpy as np
train_csv = 'train.csv'
df_train = pd.read_csv(trainData)
# define variables
target = 'SalePrice'
indep_variable = 'OverallQual'
# scoring
scoring_cross_val = 'neg_mean_squared_log_error'
scoring = mean_squared_log_error
# initate model
lin_reg = LinearRegression()
# example data
X = df_train.drop(target, axis=1)
X = X[indep_variable].to_numpy().reshape(-1, 1)
y = df_train[target].to_numpy().reshape(-1, 1)
# fit model
lin_reg.fit(X, y)
# cross validated model error
cv = cross_val_score(lin_reg, X, y, cv=2, scoring=scoring_cross_val)
</code></pre>
<p>I created a version of the code above with some simple inputs to check it isn't a bug in my version of sklearn. The code runs without a problem. </p>
<pre class="lang-py prettyprint-override"><code>from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_log_error
import pandas as pd
import numpy as np
# scoring
scoring_cross_val = 'neg_mean_squared_log_error'
scoring = mean_squared_log_error
# initate model
lin_reg = LinearRegression()
# example data
X = np.array([1.,2.,3.]).reshape(-1, 1)
y = np.array([4.,5.,6.]).reshape(-1, 1)
# fit model
lin_reg.fit(X, y)
# cross validated model error
cv = cross_val_score(lin_reg, X, y, cv=2, scoring=scoring_cross_val)
</code></pre>
<p>If anyone gets the chance to help, the csv can be downloaded from Kaggle:
<a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data" rel="nofollow noreferrer">https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data</a> </p>
<p>Iain</p>
Answer:
|
https://datascience.stackexchange.com/questions/61595/value-error-msle-crossval
|
Question: <p>I have a relatively small dataset consisting of 1432 samples.</p>
<p>I have trained a Random Forest Classifier and performed KFold CV. The results of running 10 Fold CV are as follows:</p>
<pre><code>=== 10 Fold Cross Validation Scores ===
CVFold 1 = 90.2%
CVFold 2 = 87.6%
CVFold 3 = 86.7%
CVFold 4 = 86.7%
CVFold 5 = 83.9%
CVFold 6 = 75.8%
CVFold 7 = 87.2%
CVFold 8 = 82.8%
CVFold 9 = 86.1%
CVFold 10 = 89.3%
Mean Cross Validation Score: 85.6%
</code></pre>
<p>I am just not sure how to explain why there are such high variances between some of the folds, i.e from 75.8% in fold 6 to 90.2% in fold 1.</p>
<p>My understanding is that it is simply that the classifier found the samples in the 1st fold (90%) easier to classify than it did in fold 6 (75%) but I'm actually not entirely sure if that is the case. </p>
<p>I understand that each case is different but is it common to have such variances? And is it acceptable?</p>
<p>Edit: some details regarding my data</p>
<p>I have 5 classes, which are imbalanced:</p>
<p>class 1 - 5%</p>
<p>class 2 - 10%</p>
<p>class 3 - 15%</p>
<p>class 4 - 60%</p>
<p>class 5 - 10%</p>
<p>I am using SMOTE to balance the classes.</p>
Answer: <p>It's indeed a quite large variation, but nothing alarming since 9 out of 10 folds are within the range 0.8 to 0.9. </p>
<p>There are many possible factors: yes a fold can be easier than another one by chance, but it also indicates that the training process is a bit unstable. Increasing the number of instances and/or reducing the number of features often helps reducing the variation.</p>
|
https://datascience.stackexchange.com/questions/64092/acceptable-variation-in-accuracy-of-each-k-fold-when-using-k-fold-cross-validati
|
Question: <p>I have found the following definitions, but I don't really see the difference.</p>
<p><strong>cross validation</strong>
Method for testing classification and prediction models. The data are randomly split into N partitions (typically N=10) and then N times a model is created from N-1 partitions and tested on the "holdout" data.</p>
<p><strong>Leave one out</strong>
Every data point gets to be in a test set exactly once, and gets to be in a training set k-1 times.</p>
Answer: <p>Assuming your dataset includes <span class="math-container">$k$</span> samples:</p>
<p>In cross-validation, there are <span class="math-container">$N$</span> partitions, and the test split for each partition will have size <span class="math-container">$\frac{k}{N}$</span>.</p>
<p>Leave-one-out validation is a special type of cross-validation where <span class="math-container">$N = k$</span>. You can think of this as taking cross-validation to its extreme, where we set the number of partitions to its maximum possible value. In leave-one-out validation, the test split will have size <span class="math-container">$\frac{k}{k} = 1$</span></p>
<p>It's easy to visualize the difference. Here's two figures which contrast cross-validation and leave-one-out. In these figures, each sample in the dataset is represented by a colored circle. The training set is represented by the green circles, and the testing set is represented by the yellow circles.</p>
<p>5-fold cross validation:</p>
<p><a href="https://i.sstatic.net/L7vWb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L7vWb.png" alt="5-fold cross-validation"></a></p>
<p>Leave-one-out cross validation:
<a href="https://i.sstatic.net/UqjoI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UqjoI.png" alt="leave-one-out cross validation"></a></p>
|
https://datascience.stackexchange.com/questions/64094/cross-validation-vs-leave-one-out
|
Question: <p>I would first like to create few multiple regression models based on if the models violate any multiple regression assumptions and how well it fits the training data. Then I would like to compare how well these models predict new observations by using 5-fold Cross Validation. From my understanding 5-fold Cross Validation shuffles then splits my data into 5 groups and chooses 1 for the testing set, and the other 4 for the training set. A given model is tested and the prediction error is recorded. This is repeated until all 5 groups are used as a testing set. Finally, the prediction errors are averaged.</p>
<p>My question is, when I am first determining the multiple regression equation (checking for assumptions, applying transformations, variable selection, etc.) which set of data should I use as my training set? Do I use the entire data set? Do I use one of the 5 training sets created by the 5-folds CV method? Do I repeatedly try to fit the regression model for all 5 training sets? If so, how would I extract each training set using the caret package?</p>
Answer: <p>As Peter said, you need to split your dataset into two subsets: Training, and Test sets. Generally, 80% of data is allocated for Training set (20% for the Test set).
Thereafter, depending on the language/package you use (caret in your case), you use 5- or 10-fold cross-validation to train your model, and finally, you check the prediction ability of the model using the Test set.</p>
<p>I quickly checked the Caret Package website and ripped the required code for you.</p>
<p>1- For Training-Test split:</p>
<p><a href="http://topepo.github.io/caret/data-splitting.html#" rel="nofollow noreferrer">4.1 Simple Splitting Based on the Outcome</a></p>
<pre><code>library(caret)
set.seed(3456)
trainIndex <- createDataPartition(iris$Species, p = .8,
list = FALSE,
times = 1)
</code></pre>
<p>2- For training with 10-fold cross-validation:</p>
<p><a href="http://topepo.github.io/caret/model-training-and-tuning.html" rel="nofollow noreferrer">5.3 Basic Parameter Tuning</a>,
<a href="http://topepo.github.io/caret/model-training-and-tuning.html#the-traincontrol-function" rel="nofollow noreferrer">5.5.4 The trainControl Function</a></p>
<pre><code>fitControl <- trainControl(## 10-fold CV
method = "repeatedcv",
number = 10,
## repeated the CV ten times
repeats = 10)
</code></pre>
<p>Usually, we do the cross-validation only once (repeats = 1); but to check the consitency of the results, you may need more repeats.</p>
|
https://datascience.stackexchange.com/questions/64436/multiple-linear-regression-with-k-fold-cross-validation
|
Question: <p>I have sparse vectors and found that cosine similarity is very efficient to to measure the similarity. Now I want to cluster these vectors based on similarity. Hence, can someone please suggest/recommend clustering algorithms that make use of cosine similarity?</p>
<p>P.S.: I do not have a predefined number of clusters beforehand and want the clustering algorithm itself to decide it.</p>
Answer: <p>You can see your affinity matrix as a <a href="https://en.wikipedia.org/wiki/Glossary_of_graph_theory_terms#weight" rel="nofollow noreferrer">weighted adjacency matrix</a> of a <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)" rel="nofollow noreferrer">graph</a> and apply <a href="https://en.wikipedia.org/wiki/Modularity_(networks)" rel="nofollow noreferrer">modularity</a>-based <a href="https://en.wikipedia.org/wiki/Louvain_Modularity" rel="nofollow noreferrer">community detection algorithms</a> on that. Just note that modularity based algorithms have resolution problem i.e. finding very small communities is difficult in presence of large ones.</p>
|
https://datascience.stackexchange.com/questions/20120/clustering-algorithms
|
Question: <p>How can I show clustering performance of various clustering algorithms on various datasets using adjusted mutual information and adjusted rand index.
for instance, the plot below</p>
<p>.<a href="https://i.sstatic.net/LNGbe.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LNGbe.png" alt="enter image description here" /></a></p>
Answer:
|
https://datascience.stackexchange.com/questions/106304/clustering-algorithms-evaluation
|
Question: <p>I am looking for an <strong><em>incremental</em></strong> clustering algorithm.
By <strong><em>incremental</em></strong> I mean an algorithm that builds clusters starting from an initial dataset and that is able to progressively ingest new items/observations adding them to existing or new clusters.</p>
<p>The maximum number of clusters is a priori unknow and is expected to grow over time, meaning that, after the algorithm have been run on the initial dataset, I expect to receive observations that belongs to never before seen clusters.</p>
<p>I am quite new to this kind of problem and all the clustering algorithms in the Scipy's <a href="https://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html#module-scipy.cluster.hierarchy" rel="nofollow noreferrer">clustering library</a> only provide methods for one-shot clustering.</p>
<p>The only incremental clustering algorithm offered by Scikit-learn library is the <a href="https://scikit-learn.org/0.15/modules/generated/sklearn.cluster.MiniBatchKMeans.html#sklearn.cluster.MiniBatchKMeans" rel="nofollow noreferrer">MiniBatchKMeans</a> that requires a fixed number of clusters and does not fit for my use case.</p>
<p>Are there incremental clustering algorithms that handle an unknown number of clusters? Are they already implemented somewhere?</p>
<p>Thank you a lot!</p>
Answer: <p>One option is incremental hierarchical clustering.</p>
<p><a href="https://en.wikipedia.org/wiki/Hierarchical_clustering" rel="nofollow noreferrer">Hierarchical clustering</a> either uses agglomerative or divisive approaches to divide the data into stratified groups. In hierarchical clustering, the number of clusters can be chosen during the process of building the clusters. Incremental hierarchical clustering allows data points to be added throughout the process. The paper "<a href="https://ieeexplore.ieee.org/document/8457109" rel="nofollow noreferrer">Incremental Clustering for Hierarchical Clustering</a>" by Narita, Hochin, and Nomiya goes into greater detail.</p>
|
https://datascience.stackexchange.com/questions/116664/incremental-clustering-algorithm
|
Question: <p>I have a dataset with 10,000 genes like below</p>
<pre><code>person gene1 gene2 ... gene10000 ethnic
1 0 1 1 asian
2 1 0 1 European
</code></pre>
<p>Each row means, whether a person has a gene in their DNA or not. We are trying to classify different ethnic groups based on the data above. But first we want to use some clustering algorithms to visualize how the cluster would look like for different ethnic groups. We are not going to use this clustering algorithms to classify groups, it will be used just to visualize how it would look like, if we have nice separate clusters or overlapping clusters etc.</p>
<p>Please recommend some clustering algorithms for this type of dataset. Also, the dimension is 10000. Is this going to be a problem for clustering? Should I use some dimensionality reduction algorithms first? If so please give your recommendations. Thanks in advance.</p>
Answer: <p>How many ethnic groups did you identify?</p>
<p>If I had to visualize your problem, I'd determine the key influencers for each of the ethnic groups in a Naive Bayes like approach.
These genes (gene combinations?!) (including their values) may strongly correlate to some ethnic group, while not (or inverse) correlate to another. </p>
<p>Place them on top of a pyramid graph. Place bars to the left and right for the correlation values.</p>
|
https://datascience.stackexchange.com/questions/23591/clustering-algorithms-for-high-dimensional-binary-sparse-data
|
Question: <p>I am wondering what's the best way to handle outliers when using non-supervised clustering algorithms?</p>
Answer: <p>If you have outliers, the best way is to <strong>use a clustering algorithm that can handle them</strong>.</p>
<p>For example DBSCAN clustering is robust against outliers when you choose minpts large enough. Don't use k-means: the squared error approach is sensitive to outliers. But there are variants such as k-means-- for handling outliers.</p>
|
https://datascience.stackexchange.com/questions/63695/how-to-handle-outliers-for-clustering-algorithms
|
Question: <p>I have a set of time series data that I would like to feed into a clustering algorithm (like k-means, using dynamic time warping as the distance function). After standardizing the data with mean 0 and variance 1, the k-means classifier generated a batch of centroids that seemed to fit the data pretty well.</p>
<p>The only question I have is whether the data should be stationary. Models such as ARIMA require for the data to be stationary due to the nature of it. However, the data I want to cluster is mortgage rates as a function of time, which could be subject to seasonal trends, which could be useful when clustering other future time series data.</p>
<p>The question is: do clustering algorithms for time series data generally require for the data to be stationary?</p>
Answer: <p>Have you tried replacing the entire timeseries with some meta data of it - clustering on each point of a series seems to be a bit exzessive. Especially as then if your timeseries are not synchronized they might not be considered similar - eventhough they might be for the purpose of this exercise (Imagine two sinus curves but one is slightly phase shifted -- If you would want to cluster by frequency then these would be equal). </p>
<p>So you could try to do something similar to Fourier transformations <a href="https://en.wikipedia.org/wiki/Fourier_transform" rel="nofollow noreferrer">Fourier Transformations</a>, linear fits, etc and use this meta data as input for the clustering.</p>
|
https://datascience.stackexchange.com/questions/54041/stationary-time-series-for-clustering-algorithms
|
Question: <p>As a newbie, I am interested what the major drawbacks of traditional clustering algorithms are. The purpose is to understand for which class of data or in which scenarios I shouldn't use traditional clustering methods (e.g. K-means)</p>
Answer: <p>Check out this great answer for K-means in particular:</p>
<p><a href="https://stats.stackexchange.com/questions/133656/how-to-understand-the-drawbacks-of-k-means">How to understand the drawbacks of K-means</a></p>
<p>My favorite resource for comparing the strengths and weaknesses of clustering algos is from sklearn's docs:</p>
<p><a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html" rel="nofollow noreferrer">Comparing different clustering algorithms on toy datasets
</a></p>
|
https://datascience.stackexchange.com/questions/28361/what-are-the-drawbacks-of-traditional-clustering-algorithms
|
Question: <p>Is feature scaling useful for <a href="https://en.wikipedia.org/wiki/Cluster_analysis" rel="noreferrer">clustering algorithms</a>? What type of features, I mean numeric, categorical etc., are most efficient for clustering?</p>
Answer: <p>Clustering algorithms are certainly effected by the feature scaling. </p>
<p>Example: </p>
<p>Let's say that you have two features:</p>
<ol>
<li>weight (in Lbs)</li>
<li>height (in Feet)</li>
</ol>
<p>... and we are using these to predict whether a person needs a 'S' or 'L' size shirt.</p>
<p>We are using weight+height for that, and in our trained set let's say we have two people already in clusters: </p>
<ol>
<li>Adam (175Lbs+5.9ft) in 'L'</li>
<li>Lucy (115Lbs+5.2ft) in 'S'. </li>
</ol>
<p>We have a new person - Alan (140Lbs+6.1ft.), and your clustering algo will put it in the cluster which is nearest. So, if we don't scale the features here, the height is not having much effect and Alan will be allotted in 'S' cluster.</p>
<p>So, we need to scale it. Scikit Learn provides many functions for scaling. One you can use is <code>sklearn.preprocessing.MinMaxScaler</code>. </p>
|
https://datascience.stackexchange.com/questions/22795/do-clustering-algorithms-need-feature-scaling-in-the-pre-processing-stage
|
Question: <p>Often clustering algorithms only output a bunch of class labels, and do not provide any sort of interpretation of the classes formed by the algorithm. It seems to me not entirely unreasonable to attempt to get some sort of interpretation by using the class labels provided by the clustering algorithm as the target in a supervised classification problem. </p>
<p>For a concrete example, say you cluster using k-means, and use a single decision tree classifier to predict the cluster based off of other features. The decision tree then should be able to give you some way of interpreting the clusters.</p>
<p>However, I can't find any literature (or blog posts...) mentioning this as a technique for interpreting the results of a clustering algorithm, which leads me to believe it is problematic. So in short:</p>
<blockquote>
<b>Question:</b> Can supervised classification algorithms be used to interpret the reuslts of unsupervised clustering algorithms? If not, why?
</blockquote>
Answer: <p>There's nothing wrong with this idea and although I don't have literature on hand, I'm fairly confident I've seen this sort of thing done. I disagree that clustering algorithms often don't provide interpretation though. There are definitely plenty that don't, but I'm not sure k-means is one of them. The centroids of your clusters should provide you with the interpretability you're looking for. Passing the results of k-means into a decision tree is probably just going to exchange the centroid for left and right bounds for your features (although it might actually be interesting if the tree ignores particular dimensions in the decision process). Generative models like GMM and LDA also give a lot of useful information. </p>
<p>Regarding literature, although I don't think I've seen this specifically applied to clustering, there's definitely a fair amount of on-going research into techniques for adding interpretability to "black-box models". Consider for example this article: <a href="https://arxiv.org/abs/1707.01154" rel="nofollow noreferrer">Interpretable & Explorable Approximations of Black Box Models</a></p>
<blockquote>
<p>We propose Black Box Explanations through Transparent Approximations (BETA), a novel model agnostic framework for explaining the behavior of any black-box classifier by simultaneously optimizing for fidelity to the original model and interpretability of the explanation. To this end, we develop a novel objective function which allows us to learn (with optimality guarantees), a small number of compact decision sets each of which explains the behavior of the black box model in unambiguous, well-defined regions of feature space. Furthermore, our framework also is capable of accepting user input when generating these approximations, thus allowing users to interactively explore how the black-box model behaves in different subspaces that are of interest to the user. To the best of our knowledge, this is the first approach which can produce global explanations of the behavior of any given black box model through joint optimization of unambiguity, fidelity, and interpretability, while also allowing users to explore model behavior based on their preferences. Experimental evaluation with real-world datasets and user studies demonstrates that our approach can generate highly compact, easy-to-understand, yet accurate approximations of various kinds of predictive models compared to state-of-the-art baselines.</p>
</blockquote>
<p>Poke around for "black box model interpretability" and you'll find a ton more recent research.</p>
|
https://datascience.stackexchange.com/questions/26235/using-classification-algorithms-to-interpret-clustering-reuslts
|
Question: <p>I am experimenting with clustering algorithms, like K-Means.
Right now, I use all variables as input for the clustering algorithm.
I am wondering if it is appropriate to do feature selection for clustering algorithms.
That is, how can I find those variables that are most important or least important for clustering.</p>
<p>For the case where I know what the true clusters are, my idea would be to use increasing subsets of variable combinations as input for the clustering algorithm, compute a contingency table between predicted clusters and true groups are, apply some metric (like accuracy) in order to find those feature combinations that have the worst or best score.</p>
<p>Are you aware of some method to obtain the least and most important features after applying a clustering algorithm, like k-means?</p>
<p>I am new to this topic, so please be nice. :-)</p>
Answer: <p>It is not straightforward to feature selection for k-menas clustering since it unsupervised.</p>
<p>One option is to loop through the features, leaving one out at a time. Select a criterion for better and worse clusterings, one example could be silhouette score. Then see which feature contributes the most or least to improving that criteria.</p>
<p>If you know what the true clusters are, then you have a classification problem. Should apply classification-based feature selection and algorithms.</p>
|
https://datascience.stackexchange.com/questions/103200/find-most-important-and-least-important-features-for-clustering-algorithm
|
Question: <p>I am working on a project witht the goal of clustering participants of in a survey according to their answers. The dataset is a set of 63 questions, some nominal and some ordinal. How should I encode the data before using dimensionality reduction algorithms like tsne amd then clustering algorithms like kmeans and hierarchical clustering ?</p>
Answer: <p>Although you question is quite broad, I mean you can read a whole lot of chapters out there. Still I'd mention my approach.</p>
<ol>
<li>I try to understand nature of Data i.e. look for categorical variables and
cardinality. High cardinality can pose challenges for some encoding techniques.</li>
<li>Next step is to encode. There are several encoding techniques
Label Encoding, One-Hot Encoding, Binary Encoding, Frequency Encoding,Target Encoding</li>
<li>Handle high cardinality as per your obervations.
Dimensionality Reduction Techniques: After encoding, techniques like PCA (Principal Component Analysis) or t-SNE (t-Distributed Stochastic Neighbor Embedding) to reduce dimensions.</li>
<li>Scaling and Normalization
Standardization: Adjust the encoded values to have a mean of 0 and a standard deviation of 1. This is particularly important for algorithms sensitive to scale, like PCA.
Normalization: Adjust the encoded values to fall within a specific range, typically [0, 1].</li>
<li>Feature Engineering
Combining Categories: For high-cardinality features, consider combining less frequent categories into an "Other" category to reduce dimensionality.
Creating Interaction Features: Sometimes interactions between categorical variables can be important. Creating new features based on these interactions can provide more information to the algorithms.</li>
<li>Algorithm-Specific Considerations
Clustering Algorithms: Algorithms like K-means and hierarchical clustering require numerical input and benefit from features being on a similar scale. Encodings should ensure that categorical data is represented in a way that preserves meaningful distances between points.
Dimensionality Reduction Algorithms: Algorithms like PCA, t-SNE, and UMAP (Uniform Manifold Approximation and Projection) work on numerical data and are sensitive to the scaling of input features.</li>
<li>Evaluation and Iteration
Visualization: Use visualization techniques like pair plots or heatmaps to understand the relationships and distributions of encoded features.
Model Performance: Evaluate the performance of clustering algorithms and dimensionality reduction techniques using metrics like silhouette score, Davies-Bouldin index, or explained variance ratio for PCA.</li>
</ol>
<p>Iterate: Experiment with different encoding techniques and preprocessing steps to find the best combination for your specific dataset and task.</p>
<p>Example Workflow
<em>Identify categorical variables: Country, Gender, Job Title.
Choose encoding techniques:
Country: One-hot encoding.
Gender: Label encoding.
Job Title: Frequency encoding.
Encode the data.
Scale the data: Apply standardization.
Apply dimensionality reduction: Use PCA to reduce dimensions.
Cluster the data: Use K-means clustering.</em>
Evaluate results: Check cluster quality using silhouette score.</p>
<p><a href="https://www.ibm.com/topics/dimensionality-reduction" rel="nofollow noreferrer">Dimensionality Reduction</a>
<a href="https://www.geeksforgeeks.org/dimensionality-reduction" rel="nofollow noreferrer">Dimensionality Reduction important points</a></p>
|
https://datascience.stackexchange.com/questions/129530/how-to-preprocess-encode-categorical-data-to-use-in-dimensionality-reduction-an
|
Question: <p>I am trying to compare different clustering algorithms for my text data. I first calculated the tf-idf matrix and used it for the cosine distance matrix (cosine similarity). Then I used this distance matrix for K-means and Hierarchical clustering (ward and dendrogram). I want to use the distance matrix for mean-shift, DBSCAN, and optics. </p>
<p>Below is the part of the code showing the distance matrix. </p>
<pre><code>from sklearn.feature_extraction.text import TfidfVectorizer
#define vectorizer parameters
tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,
min_df=0.2, stop_words='english',
use_idf=True, tokenizer=tokenize_and_stem, ngram_range=(1,3))
%time tfidf_matrix = tfidf_vectorizer.fit_transform(Strategies) #fit the vectorizer to synopses
terms = tfidf_vectorizer.get_feature_names()
from sklearn.metrics.pairwise import cosine_similarity
dist = 1 - cosine_similarity(tfidf_matrix)
print(dist)
</code></pre>
<p>I am new to both python and clustering. I found the code for K-means and hierarchical clustering and tried to understand it but I cannot apply it for other clusterings algorithms.
It would be very helpful if I can get some simple explanation of each clustering algorithm and how this distance matrix can be used to implement (if possible) in different clustering.</p>
<p>Thanks in advance!</p>
Answer: <p>Several scikit-learn clustering algorithms can be fit using cosine distances:</p>
<pre class="lang-py prettyprint-override"><code>from collections import defaultdict
from sklearn.datasets import load_iris
from sklearn.cluster import DBSCAN, OPTICS
# Define sample data
iris = load_iris()
X = iris.data
# List clustering algorithms
algorithms = [DBSCAN, OPTICS] # MeanShift does not use a metric
# Fit each clustering algorithm and store results
results = defaultdict(int)
for algorithm in algorithms:
results[algorithm] = algorithm(metric='cosine').fit(X)
</code></pre>
|
https://datascience.stackexchange.com/questions/69183/how-to-use-cosine-distance-matrix-for-clustering-algorithms-like-mean-shift-dbs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.