问题
My confusion matrix code will be like this
confusionmatrix = pd.DataFrame(
confusion_matrix(test["Churn"], predictions),
columns=["Predicted False", "Predicted True"], index=["Actual False", "Actual True"]
)
I am getting results like this
Predicted False Predicted True
Actual False 877 100
Actual True 183 179
After i converted this above confusion matrix results to json. My json results would be like this
results = [{'confusionmatrix' : confusionmatrix}]
final = pd.Series(results).to_json(orient='records')
[
{
"confusionmatrix": [
{
"Predicted False": 877,
"Predicted True": 100
},
{
"Predicted False": 183,
"Predicted True": 179
}
]
}
]
But, my expected output need to be like this,
[
{
"confusionmatrix": [
{
"Actual": "False",
"Predict": "False",
"value": 894
},
{
"Actual": "False",
"Predict": "True",
"value": 125
}
]
}
]
Where can i change my code for getting results like this?
回答1:
I think need:
df = pd.DataFrame(confusion_matrix(test["Churn"], predictions),
columns=["False", "True"],
index=["False", "True"])
df.index.name= 'Actual'
df.columns.name= 'Predicted'
print (df)
Predicted False True
Actual
False 877 183
True 100 179
confusionmatrix = df.unstack().rename('value').reset_index()
print (confusionmatrix)
Predicted Actual value
0 False False 877
1 False True 100
2 True False 183
3 True True 179
results = [{'confusionmatrix' : confusionmatrix}]
final = pd.Series(results).to_json(orient='records')
print (final)
[{"confusionmatrix":[{"Predicted":"False","Actual":"False","value":877},
{"Predicted":"False","Actual":"True","value":100},
{"Predicted":"True","Actual":"False","value":183},
{"Predicted":"True","Actual":"True","value":179}]}]
来源:https://stackoverflow.com/questions/49689785/confusion-matrix-format-after-converting-to-json-results-using-python