使用python的多模型准确性json结果格式 [英] multiple model accuracy json result format using python

查看:59
本文介绍了使用python的多模型准确性json结果格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个多模型,并且我获得7个模型精度的结果,我需要使用正确的json格式的结果.

I am building a multiple model and i am getting results with 7 models accuracy, i need those results with a proper json format.

我的多模型构建代码将是这样

My multiple model building code will be like this

种子= 7

"prepare models"

models = []
models.append(('LogisticRegression', LogisticRegression()))
models.append(('LinearDiscriminantAnalysis', LinearDiscriminantAnalysis()))
models.append(('KNeighborsClassifier', KNeighborsClassifier()))
models.append(('DecisionTreeClassifier', DecisionTreeClassifier()))
models.append(('GaussianNB', GaussianNB()))
models.append(('RandomForestClassifier',RandomForestClassifier()))
models.append(('SVC', SVC()))

"evaluate each model in turn"

results = []
names = []
kfold_result = {}
scoring = 'accuracy'

# Kfold model selection

for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=seed)
    cv_results = model_selection.cross_val_score(model, train[features_train],train["Churn"], cv=kfold, scoring=scoring)
    results.append(cv_results)
    names.append('"%s"' %name)
    # Appending result in new dictionary
    kfold_result[name] = cv_results.mean()
    model_results = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
#print(model_results)

# For testing im just printing the dictionary values

#print(kfold_result)
#type(kfold_result)

from collections import OrderedDict
sorted_model = OrderedDict(sorted(kfold_result.items(), key = lambda x:x[1], reverse = True))
#    print(sorted_model)
#    type(sorted_model)

    # make predictions on validation dataset

for key in sorted_model.keys():
    print(key)
    break

# if condition

if(key == "SVC"):
    prediction_model = SVC()
elif(key == "RandomForestClassifier"):
    prediction_model = RandomForestClassifier()
elif(key == "GaussianNB"):
    prediction_model = GaussianNB()
elif(key == "DecisionTreeClassifier"):
    prediction_model = DecisionTreeClassifier()
elif(key == "KNeighborsClassifier"):
    prediction_model = KNeighborsClassifier()
elif(key == "LinearDiscriminantAnalysis"):
    prediction_model = LinearDiscriminantAnalysis()
elif(key == "LogisticRegression"):
    prediction_model = LogisticRegression()

prediction_model.fit(train[features_train], train["Churn"])
predictions = prediction_model.predict(test[features_test])
Model_accuracy = accuracy_score(test["Churn"], predictions)

对于这种排序的多个模型,我得到的是json结果

I am getting a json results for this sorted multiple model accuracy will be like this

"sorted_model_results": {
            "LogisticRegression": 0.801307365,
            "LinearDiscriminantAnalysis": 0.7919713349,
            "SVC": 0.7490145069,
            "KNeighborsClassifier": 0.7576049658,
            "DecisionTreeClassifier": 0.7200680011,
            "RandomForestClassifier": 0.7775861347,
            "GaussianNB": 0.7521913796
        }

但是,我的预期输出必须是这样,

But, my expected output have to be like this,

[
    {
        "model": [
            {
                "model_name": "LogisticRegression",
                "model_accuracy": 80.131
            },
            {
                "model_name": "LinearDiscriminantAnalysis",
                "model_accuracy": 80.131
            }
        ]
    }
]

我需要类似上述格式的json结果.如何更改我的代码以获得这样的json结果

i need the json results like above format. how to change my code to get the json results like this

推荐答案

from collections import OrderedDict
    sorted_model = dict(OrderedDict(sorted(kfold_result.items(), key = lambda x:x[1], reverse = True)))

    s = pd.Series(sorted_model)

    a = pd.DataFrame(s).reset_index()

    sorted_models = a.rename(columns={'index':'model_name', 0 : 'model_accuracy'})

通过将dict转换为series和dataframe,我得到了预期的输出,然后我重命名了dataframe的列名.最后,我将结果转换为json.

I got the expected output by converting the dict to series and to dataframe, then i rename the column names of dataframe. Finally i converted the results to json.

我的输出

[
    {
        "model": [
            {
                "model_name": "LogisticRegression",
                "model_accuracy": 80.131
            },
            {
                "model_name": "LinearDiscriminantAnalysis",
                "model_accuracy": 80.131
            }
        ]
    }
]

这篇关于使用python的多模型准确性json结果格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆