pau*_*a.n 7 python matplotlib legend mse neural-network
我是一个Python初学者,所以这可能比我想象的更明显。我用来Matplotlib通过神经网络以图形方式呈现我的预测数据与实际数据。我能够计算 r 平方并绘制数据,但现在我想合并图表本身上的值,该值会随着每次新运行而变化。
我的神经网络至少使用 4 个不同的输入,并给出一个输出。这是我的最终代码:
y_predicted = model.predict(X_test)
Run Code Online (Sandbox Code Playgroud)
这就是我计算 R2 的方法:
# Using sklearn
from sklearn.metrics import r2_score
print r2_score(y_test, y_predicted)
Run Code Online (Sandbox Code Playgroud)
这是我的图表:
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()
Run Code Online (Sandbox Code Playgroud)
它给出了类似于所附图表的内容,每次我更改纪元、层数或数据类型等时,R2 都会发生变化。红色是我的回归线,稍后我将对其进行标记。由于 R2 是一个函数,我不能简单地使用图例或文本代码。
我还想展示MSE。
谁能帮我吗?
小智 9
如果您想将 r 平方值放在图表本身上,就像 Microsoft Excel 中的图表一样,您可以调用以下annotate方法:
ax.annotate("r-squared = {:.3f}".format(r2_score(y_test, y_predicted)), (0, 1))
Run Code Online (Sandbox Code Playgroud)
或者
plt.annotate("r-squared = {:.3f}".format(r2_score(y_test, y_predicted)), (0, 1))
Run Code Online (Sandbox Code Playgroud)
第一个参数是您希望放置在图表上的文本,第二个参数是该文本左下角的位置。如果您想添加另一行,例如 MSE,您可以将“\n”和您想要的任何文本附加到第一个参数。请记住,(x, y) 元组会根据数据进行缩放,因此如果您的数据范围不是 [0, 1],并且您希望将文本放置在左上角,则可能需要更改来自 (0, 1) 的第二个参数。
有关更多信息,请参阅https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.axes.Axes.annotate.html或https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot .annotate.html
小智 4
如果我理解正确的话,你想在图中显示 R2 。您可以将其添加到图表标题中:
ax.set_title('R2: ' + str(r2_score(y_test, y_predicted)))
Run Code Online (Sandbox Code Playgroud)
前plt.show()