multiple model accuracy json result format using python

2024/9/20 21:45:50

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 selectionfor 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 dictionarykfold_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 datasetfor key in sorted_model.keys():print(key)break# if conditionif(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

Answer
from collections import OrderedDictsorted_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}]}
]
https://en.xdnf.cn/q/119278.html

Related Q&A

Calculate Time Difference based on Conditionals

I have a dataframe that looks something like this (actual dataframe is millions of rows):ID Category Site Task Completed Access Completed1 A X 1/2/22 12:00:00AM 1/1/22 12:00:00 AM1 A Y 1/3/22 12:00:00A…

Cannot open jpg images with PIL or open()

I am testing to save ImageField in Django, but for some reason all the *.jpg files Ive tried dont work while the one png I had works. Using django shell in WSL VCode terminal. python 3.7 django 3.0 pil…

how to delete tensorflow model before retraining

I cant retrain my image classifier with new images, I get the following error:AssertionError: Export directory already exists. Please specify a different export directory: /tmp/saved_models/1/How do I …

Use beautifulsoup to scrape a table within a webpage?

I am scraping a county website that posts emergency calls and their locations. I have found success webscraping basic elements, but am having trouble scraping the rows of the table. (Here is an example…

Encrypt folder or zip file using python

So I am trying to encrypt a directory using python and Im not sure what the best way to do that is. I am easily able to turn the folder into a zip file, but from there I have tried looking up how to en…

Use Python Element Tree to parse xml in ASCII text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Time series plot showing unique occurrences per day

I have a dataframe, where I would like to make a time series plot with three different lines that each show the daily occurrences (the number of rows per day) for each of the values in another column. …

Problem accessing indexed results two stage stochastic programming Pyomo

When running a stochastic programming problem in Pyomo, the resulting solution works only when running 10 precisely the same scenarios but the results remain zero when running different scenarios. I ai…

Pandas python + format for values

This is the code:import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as pltdf.head(3).style.format({Budget: "€ {:,.0f}"}) Year …

Is there any implementation of deconvolution?

Some one may prefer to call it the transposed convolution, as introduced here. Im looking forward to an implementation of the transposed convolution, in Python or C/C++. Thank you all for helping me!