working with an extremely unbalanced and poorly correlated dataset












1














Hi I am working with a difficult data set, in that the classes are both highly unbalanced and extremely uncorrelated (The set has 96,000 values, of which less than 200 are 1s.). I tried a few methods, and with each the precision and accuracy were always high, however only a few (less than 5) values are being classified as 1. I wonder if there is a way to force the machine to classify more 1s. If I could classify correctly just 25% of the time, this would be a great result.



I have tried using random forest's 'class weight' parameter, but this doesn't seem to have any effect on the result.



Thanks



import numpy as np
import pandas as pd
import sklearn as sklearn
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_pickle('/Users/shellyganga/Downloads/ola.pickle')

print(df.describe())

#filtering the df to improve results
df = df[(df['trip_duration'] > 5) & (df['Smooth_Driving_Score'] < 99)]

print(df.describe())


maxVal = 1
df.unsafe = df['unsafe'].where(df['unsafe'] <= maxVal, maxVal)

df.drop(df.columns[0], axis=1, inplace=True)
df.drop(df.columns[-2], axis=1, inplace=True)

#setting features and labels
labels = np.array(df['unsafe'])
features= df.drop('unsafe', axis = 1)

# Saving feature names for later use
feature_list = list(features.columns)

# Convert to numpy array
features = np.array(features)

from sklearn.model_selection import train_test_split

# 30% examples in test data
train, test, train_labels, test_labels = train_test_split(features, labels,
stratify = labels,
test_size = 0.4,
random_state = 12)

from sklearn.ensemble import RandomForestClassifier

# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100,
random_state=12,
max_features = 'sqrt',
n_jobs=-1, verbose = 1, class_weight={0:1, 1:1})

# Fit on training data
model.fit(train, train_labels)
predictions = model.predict(test)


print(np.mean(predictions))
print(predictions.shape)


from sklearn.metrics import classification_report
print(classification_report(test_labels, predictions)


ouput



     precision    recall  f1-score   support

0 1.00 1.00 1.00 38300
1 1.00 0.01 0.02 90

avg / total 1.00 1.00 1.00 38390


edit: I tried using {class_weight = 'balanced'} and provided a different result, but I am having trouble understanding it.



   micro avg       1.00      1.00      1.00     38390
macro avg 1.00 0.51 0.51 38390
weighted avg 1.00 1.00 1.00 38390


How do I know how many positives it has predicted?










share|improve this question




















  • 1




    class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
    – Luke
    Nov 17 '18 at 20:46






  • 1




    thanks, I added an edit with the output I got but I still don't understand it
    – user3107977
    Nov 18 '18 at 8:17
















1














Hi I am working with a difficult data set, in that the classes are both highly unbalanced and extremely uncorrelated (The set has 96,000 values, of which less than 200 are 1s.). I tried a few methods, and with each the precision and accuracy were always high, however only a few (less than 5) values are being classified as 1. I wonder if there is a way to force the machine to classify more 1s. If I could classify correctly just 25% of the time, this would be a great result.



I have tried using random forest's 'class weight' parameter, but this doesn't seem to have any effect on the result.



Thanks



import numpy as np
import pandas as pd
import sklearn as sklearn
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_pickle('/Users/shellyganga/Downloads/ola.pickle')

print(df.describe())

#filtering the df to improve results
df = df[(df['trip_duration'] > 5) & (df['Smooth_Driving_Score'] < 99)]

print(df.describe())


maxVal = 1
df.unsafe = df['unsafe'].where(df['unsafe'] <= maxVal, maxVal)

df.drop(df.columns[0], axis=1, inplace=True)
df.drop(df.columns[-2], axis=1, inplace=True)

#setting features and labels
labels = np.array(df['unsafe'])
features= df.drop('unsafe', axis = 1)

# Saving feature names for later use
feature_list = list(features.columns)

# Convert to numpy array
features = np.array(features)

from sklearn.model_selection import train_test_split

# 30% examples in test data
train, test, train_labels, test_labels = train_test_split(features, labels,
stratify = labels,
test_size = 0.4,
random_state = 12)

from sklearn.ensemble import RandomForestClassifier

# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100,
random_state=12,
max_features = 'sqrt',
n_jobs=-1, verbose = 1, class_weight={0:1, 1:1})

# Fit on training data
model.fit(train, train_labels)
predictions = model.predict(test)


print(np.mean(predictions))
print(predictions.shape)


from sklearn.metrics import classification_report
print(classification_report(test_labels, predictions)


ouput



     precision    recall  f1-score   support

0 1.00 1.00 1.00 38300
1 1.00 0.01 0.02 90

avg / total 1.00 1.00 1.00 38390


edit: I tried using {class_weight = 'balanced'} and provided a different result, but I am having trouble understanding it.



   micro avg       1.00      1.00      1.00     38390
macro avg 1.00 0.51 0.51 38390
weighted avg 1.00 1.00 1.00 38390


How do I know how many positives it has predicted?










share|improve this question




















  • 1




    class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
    – Luke
    Nov 17 '18 at 20:46






  • 1




    thanks, I added an edit with the output I got but I still don't understand it
    – user3107977
    Nov 18 '18 at 8:17














1












1








1







Hi I am working with a difficult data set, in that the classes are both highly unbalanced and extremely uncorrelated (The set has 96,000 values, of which less than 200 are 1s.). I tried a few methods, and with each the precision and accuracy were always high, however only a few (less than 5) values are being classified as 1. I wonder if there is a way to force the machine to classify more 1s. If I could classify correctly just 25% of the time, this would be a great result.



I have tried using random forest's 'class weight' parameter, but this doesn't seem to have any effect on the result.



Thanks



import numpy as np
import pandas as pd
import sklearn as sklearn
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_pickle('/Users/shellyganga/Downloads/ola.pickle')

print(df.describe())

#filtering the df to improve results
df = df[(df['trip_duration'] > 5) & (df['Smooth_Driving_Score'] < 99)]

print(df.describe())


maxVal = 1
df.unsafe = df['unsafe'].where(df['unsafe'] <= maxVal, maxVal)

df.drop(df.columns[0], axis=1, inplace=True)
df.drop(df.columns[-2], axis=1, inplace=True)

#setting features and labels
labels = np.array(df['unsafe'])
features= df.drop('unsafe', axis = 1)

# Saving feature names for later use
feature_list = list(features.columns)

# Convert to numpy array
features = np.array(features)

from sklearn.model_selection import train_test_split

# 30% examples in test data
train, test, train_labels, test_labels = train_test_split(features, labels,
stratify = labels,
test_size = 0.4,
random_state = 12)

from sklearn.ensemble import RandomForestClassifier

# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100,
random_state=12,
max_features = 'sqrt',
n_jobs=-1, verbose = 1, class_weight={0:1, 1:1})

# Fit on training data
model.fit(train, train_labels)
predictions = model.predict(test)


print(np.mean(predictions))
print(predictions.shape)


from sklearn.metrics import classification_report
print(classification_report(test_labels, predictions)


ouput



     precision    recall  f1-score   support

0 1.00 1.00 1.00 38300
1 1.00 0.01 0.02 90

avg / total 1.00 1.00 1.00 38390


edit: I tried using {class_weight = 'balanced'} and provided a different result, but I am having trouble understanding it.



   micro avg       1.00      1.00      1.00     38390
macro avg 1.00 0.51 0.51 38390
weighted avg 1.00 1.00 1.00 38390


How do I know how many positives it has predicted?










share|improve this question















Hi I am working with a difficult data set, in that the classes are both highly unbalanced and extremely uncorrelated (The set has 96,000 values, of which less than 200 are 1s.). I tried a few methods, and with each the precision and accuracy were always high, however only a few (less than 5) values are being classified as 1. I wonder if there is a way to force the machine to classify more 1s. If I could classify correctly just 25% of the time, this would be a great result.



I have tried using random forest's 'class weight' parameter, but this doesn't seem to have any effect on the result.



Thanks



import numpy as np
import pandas as pd
import sklearn as sklearn
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_pickle('/Users/shellyganga/Downloads/ola.pickle')

print(df.describe())

#filtering the df to improve results
df = df[(df['trip_duration'] > 5) & (df['Smooth_Driving_Score'] < 99)]

print(df.describe())


maxVal = 1
df.unsafe = df['unsafe'].where(df['unsafe'] <= maxVal, maxVal)

df.drop(df.columns[0], axis=1, inplace=True)
df.drop(df.columns[-2], axis=1, inplace=True)

#setting features and labels
labels = np.array(df['unsafe'])
features= df.drop('unsafe', axis = 1)

# Saving feature names for later use
feature_list = list(features.columns)

# Convert to numpy array
features = np.array(features)

from sklearn.model_selection import train_test_split

# 30% examples in test data
train, test, train_labels, test_labels = train_test_split(features, labels,
stratify = labels,
test_size = 0.4,
random_state = 12)

from sklearn.ensemble import RandomForestClassifier

# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100,
random_state=12,
max_features = 'sqrt',
n_jobs=-1, verbose = 1, class_weight={0:1, 1:1})

# Fit on training data
model.fit(train, train_labels)
predictions = model.predict(test)


print(np.mean(predictions))
print(predictions.shape)


from sklearn.metrics import classification_report
print(classification_report(test_labels, predictions)


ouput



     precision    recall  f1-score   support

0 1.00 1.00 1.00 38300
1 1.00 0.01 0.02 90

avg / total 1.00 1.00 1.00 38390


edit: I tried using {class_weight = 'balanced'} and provided a different result, but I am having trouble understanding it.



   micro avg       1.00      1.00      1.00     38390
macro avg 1.00 0.51 0.51 38390
weighted avg 1.00 1.00 1.00 38390


How do I know how many positives it has predicted?







python scikit-learn classification weight






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 8:15







user3107977

















asked Nov 17 '18 at 18:14









user3107977user3107977

233




233








  • 1




    class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
    – Luke
    Nov 17 '18 at 20:46






  • 1




    thanks, I added an edit with the output I got but I still don't understand it
    – user3107977
    Nov 18 '18 at 8:17














  • 1




    class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
    – Luke
    Nov 17 '18 at 20:46






  • 1




    thanks, I added an edit with the output I got but I still don't understand it
    – user3107977
    Nov 18 '18 at 8:17








1




1




class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
– Luke
Nov 17 '18 at 20:46




class_weight is the way to do it. What values did you try? From the docs, it looks like you should try class_weight='balanced' which will automatically create something roughly like {0:(200.0/96000), 1:1}
– Luke
Nov 17 '18 at 20:46




1




1




thanks, I added an edit with the output I got but I still don't understand it
– user3107977
Nov 18 '18 at 8:17




thanks, I added an edit with the output I got but I still don't understand it
– user3107977
Nov 18 '18 at 8:17












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354123%2fworking-with-an-extremely-unbalanced-and-poorly-correlated-dataset%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354123%2fworking-with-an-extremely-unbalanced-and-poorly-correlated-dataset%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Can I use Tabulator js library in my java Spring + Thymeleaf project?