confusion matrix format after converting to json results using python

人盡茶涼 提交于 2019-12-11 01:04:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!