How to plot heatmap based on GradientBoost results?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?Select rows from a DataFrame based on values in a column in pandas

Where can/should I, as a high schooler, publish a paper regarding the derivation of a formula?

How much does Commander Data weigh?

Very slow boot time and poor perfomance

Does Yeshayahu 43:10b / 43:13a imply HaShem was created?

Are there any elected officials in the U.S. who are not legislators, judges, or constitutional officers?

Tex Quotes(UVa 272)

To get so rich that you are not in need of anymore money

How many lines of code does the original TeX contain?

How do I make my image comply with the requirements of this photography competition?

Do Bayesian credible intervals treat the estimated parameter as a random variable?

What should come first—characters or plot?

Why do these two functions have the same bytecode when disassembled under dis.dis?

Higman's lemma and a manuscript of Erdős and Rado

If the Shillelagh cantrip is applied to a club with non-standard damage dice, what is the resulting damage dice?

Why doesn't 'd /= d' throw a division by zero exception?

Does ostensible/specious make sense in this sentence?

When one problem is added to the previous one

"There were either twelve sexes or none."

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

How long do you think advanced cybernetic implants would plausibly last?

Limitations with dynamical systems vs. PDEs?

Joining lists with same elements

When, exactly, does the Rogue Scout get to use their Skirmisher ability?

How many birds in the bush?



How to plot heatmap based on GradientBoost results?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?Select rows from a DataFrame based on values in a column in pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I want to print a heatmap of a confusion matrix based on my results of y_predict and y_train.



I'm a bit stuck and I already looked up the pandas documentation of the heatmap, but still don't know how to apply it on my results. The dataset I used is about incomes and has categorical and numerical data. I've already applied the GB classifier and I got an result.
The only thing that remains is the heatmap.



print(confusion_matrix(y_train,y_pred_train))
print(y_train)


this was the outcome



Confusion Matrix:


[[14151 710]
[ 1844 2831]]
Name: income, Length: 19536, dtype: int64


this was an attempt to make a heatmap



import seaborn as sns
class_names = y_train, y_pred_train

def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig


which returned



NameError Traceback (most recent call last)
<ipython-input-36-3bd0e9ee90a4> in <module>()
18 plt.xlabel('Predicted label')
19 return fig
---> 20 print(fig)

NameError: name 'fig' is not defined



So what am I missing when I'm making the heatmap of the confusion matrix on my results?










share|improve this question


























  • You can call the function with your confusion matrix, see my answer for an example

    – perl
    Mar 27 at 19:52












  • And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

    – perl
    Mar 27 at 20:00

















0















I want to print a heatmap of a confusion matrix based on my results of y_predict and y_train.



I'm a bit stuck and I already looked up the pandas documentation of the heatmap, but still don't know how to apply it on my results. The dataset I used is about incomes and has categorical and numerical data. I've already applied the GB classifier and I got an result.
The only thing that remains is the heatmap.



print(confusion_matrix(y_train,y_pred_train))
print(y_train)


this was the outcome



Confusion Matrix:


[[14151 710]
[ 1844 2831]]
Name: income, Length: 19536, dtype: int64


this was an attempt to make a heatmap



import seaborn as sns
class_names = y_train, y_pred_train

def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig


which returned



NameError Traceback (most recent call last)
<ipython-input-36-3bd0e9ee90a4> in <module>()
18 plt.xlabel('Predicted label')
19 return fig
---> 20 print(fig)

NameError: name 'fig' is not defined



So what am I missing when I'm making the heatmap of the confusion matrix on my results?










share|improve this question


























  • You can call the function with your confusion matrix, see my answer for an example

    – perl
    Mar 27 at 19:52












  • And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

    – perl
    Mar 27 at 20:00













0












0








0








I want to print a heatmap of a confusion matrix based on my results of y_predict and y_train.



I'm a bit stuck and I already looked up the pandas documentation of the heatmap, but still don't know how to apply it on my results. The dataset I used is about incomes and has categorical and numerical data. I've already applied the GB classifier and I got an result.
The only thing that remains is the heatmap.



print(confusion_matrix(y_train,y_pred_train))
print(y_train)


this was the outcome



Confusion Matrix:


[[14151 710]
[ 1844 2831]]
Name: income, Length: 19536, dtype: int64


this was an attempt to make a heatmap



import seaborn as sns
class_names = y_train, y_pred_train

def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig


which returned



NameError Traceback (most recent call last)
<ipython-input-36-3bd0e9ee90a4> in <module>()
18 plt.xlabel('Predicted label')
19 return fig
---> 20 print(fig)

NameError: name 'fig' is not defined



So what am I missing when I'm making the heatmap of the confusion matrix on my results?










share|improve this question
















I want to print a heatmap of a confusion matrix based on my results of y_predict and y_train.



I'm a bit stuck and I already looked up the pandas documentation of the heatmap, but still don't know how to apply it on my results. The dataset I used is about incomes and has categorical and numerical data. I've already applied the GB classifier and I got an result.
The only thing that remains is the heatmap.



print(confusion_matrix(y_train,y_pred_train))
print(y_train)


this was the outcome



Confusion Matrix:


[[14151 710]
[ 1844 2831]]
Name: income, Length: 19536, dtype: int64


this was an attempt to make a heatmap



import seaborn as sns
class_names = y_train, y_pred_train

def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig


which returned



NameError Traceback (most recent call last)
<ipython-input-36-3bd0e9ee90a4> in <module>()
18 plt.xlabel('Predicted label')
19 return fig
---> 20 print(fig)

NameError: name 'fig' is not defined



So what am I missing when I'm making the heatmap of the confusion matrix on my results?







python pandas machine-learning seaborn






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 0:13









Brian

9458 silver badges19 bronze badges




9458 silver badges19 bronze badges










asked Mar 27 at 19:16









b34tsb34ts

11 bronze badge




11 bronze badge















  • You can call the function with your confusion matrix, see my answer for an example

    – perl
    Mar 27 at 19:52












  • And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

    – perl
    Mar 27 at 20:00

















  • You can call the function with your confusion matrix, see my answer for an example

    – perl
    Mar 27 at 19:52












  • And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

    – perl
    Mar 27 at 20:00
















You can call the function with your confusion matrix, see my answer for an example

– perl
Mar 27 at 19:52






You can call the function with your confusion matrix, see my answer for an example

– perl
Mar 27 at 19:52














And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

– perl
Mar 27 at 20:00





And the error on print(fig) is that fig is defined inside the function, and if you want to use it outside the scope of the function, you can set it with fig = print_confusion_matrix(... since it's returned from your function with return fig

– perl
Mar 27 at 20:00












1 Answer
1






active

oldest

votes


















0















You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:



def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])


Output:



enter image description here






share|improve this answer




















  • 1





    Thank you very much for your help!

    – b34ts
    Mar 27 at 20:55










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%2f55384928%2fhow-to-plot-heatmap-based-on-gradientboost-results%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0















You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:



def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])


Output:



enter image description here






share|improve this answer




















  • 1





    Thank you very much for your help!

    – b34ts
    Mar 27 at 20:55















0















You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:



def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])


Output:



enter image description here






share|improve this answer




















  • 1





    Thank you very much for your help!

    – b34ts
    Mar 27 at 20:55













0














0










0









You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:



def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])


Output:



enter image description here






share|improve this answer













You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:



def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
df_cm = pd.DataFrame(
confusion_matrix, index=class_names, columns=class_names,
)
fig = plt.figure(figsize=figsize)
try:
heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
except ValueError:
raise ValueError("Confusion matrix values must be integers.")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])


Output:



enter image description here







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 19:52









perlperl

2,1014 silver badges17 bronze badges




2,1014 silver badges17 bronze badges










  • 1





    Thank you very much for your help!

    – b34ts
    Mar 27 at 20:55












  • 1





    Thank you very much for your help!

    – b34ts
    Mar 27 at 20:55







1




1





Thank you very much for your help!

– b34ts
Mar 27 at 20:55





Thank you very much for your help!

– b34ts
Mar 27 at 20:55






Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55384928%2fhow-to-plot-heatmap-based-on-gradientboost-results%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

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript