9951 explained code solutions for 126 technologies


python-scikit-learnHow to calculate MAPE (mean absolute percentage error)


from sklearn import datasets, linear_model, model_selection, metrics

X, y = datasets.load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y)

model = linear_model.LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

mape = metrics.mean_absolute_percentage_error(y_test, y_pred)ctrl + c
from sklearn import

import module from scikit-learn

datasets.load_diabetes

loads sample diabetes database

model_selection.train_test_split

splits given X and y datasets to test (25% of values by default) and train (75% of values by default) subsets

.fit(

train model with a given features and target variable dataset

.predict(

predict target variable based on given features dataset

.mean_absolute_percentage_error(

calculates MAPE for the trained model


Usage example

from sklearn import datasets, linear_model, model_selection, metrics

X, y = datasets.load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y)

model = linear_model.LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

mape = metrics.mean_absolute_percentage_error(y_test, y_pred)
print(mape)
output
0.3677663393932409