How to display R-squared value on my graph in Python

paula.n picture paula.n · Jan 20, 2020 · Viewed 9.7k times · Source

I am a Python beginner so this may be more obvious than what I'm thinking. I'm using Matplotlib to graphically present my predicted data vs actual data via a neural network. I am able to calculate r-squared, and plot my data, but now I want to combine the value on the graph itself, which changes with every new run.

My NN uses at least 4 different inputs, and gives one output. This is my end code for that:

y_predicted = model.predict(X_test)

This is how i calculate R2:

# Using sklearn
from sklearn.metrics import r2_score
print r2_score(y_test, y_predicted)

and this is my graph:

fig, ax = plt.subplots()
ax.scatter(y_test, y_predicted)
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
ax.set_xlabel('Actual')
ax.set_ylabel('Predicted')
#regression line
y_test, y_predicted = y_test.reshape(-1,1), y_predicted.reshape(-1,1)
ax.plot(y_test, LinearRegression().fit(y_test, y_predicted).predict(y_test))

plt.show()

It gives something like the graph attached, and the R2 varies everytime I change the epochs, or number of layers, or type of data etc. The red is my line of regression, which I will label later. Since R2 is a function I can't simply use the legend or text code.

I would also like to display MSE.

Can anyone help me out?

Graph

Answer

Ioanna picture Ioanna · Jan 20, 2020

If I understand correctly, you want to show R2 in the graph. You can add it to the graph title:

ax.set_title('R2: ' + str(r2_score(y_test, y_predicted)))

before plt.show()