Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

seed = 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)

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
            }
        ]
    }
]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'})

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.

My output,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...