You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制ANN损失曲线时报错TypeError: plot()缺少参数'ys'

解决Matplotlib旧版本中plt.plot()报TypeError: missing 'ys'参数的问题

我在跟着TensorFlow 2.0在线课程做人工神经网络(ANN)基础绘图时遇到问题:在Colab的Jupyter Notebooks里用Matplotlib 3.6.2运行一切正常,但在VS Code搭配TensorFlow 2.3.0运行控制台时出现报错。

报错信息如下:

Traceback (most recent call last):
  File "annr.py", line 43, in <module>
    plt.plot(r.history['loss'], label='loss')
  File "C:\Users\calem\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\pyplot.py", line 2842, in plot
    **({"data": data} if data is not None else {}), **kwargs)
TypeError: plot() missing 1 required positional argument: 'ys'

截至报错位置的完整脚本:

import tensorflow as tf
print('tf version:' + tf.__version__)

# %% [markdown]
# 

# %%
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# %%
# Make the dataset
N = 1000
X = np.random.random((N, 2)) * 6 - 3 # uniformly distributed (-3, +3)
Y = np.cos(2*X[:,0]) + np.cos(3*X[:,1])

# %%
# y = cos(2x_1) + cos(3x_2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:,0], X[:,1], Y)
# plt.show()

# %%


# %%
# Build the model
model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(128, input_shape=(2,), activation='relu'),
  tf.keras.layers.Dense(1)
])

# %%
# Compile and fit & plot the loss
opt = tf.keras.optimizers.Adam(0.01)
model.compile(optimizer=opt, loss='mse')
r = model.fit(X, Y, epochs=100)
# Plot the loss
plt.plot(r.history['loss'], label='loss')

问题原因

这个错误源于你使用的Matplotlib版本过旧。在较老的Matplotlib版本中,plt.plot()要求必须明确传入x轴和y轴两组数据;而Matplotlib 3.6.2这类新版本已经支持仅传入y轴数据(自动生成从0开始的x轴序列),这就是代码在Colab能正常运行、本地却报错的核心原因。

修复方法

方式1:明确传入x轴数据

修改绘图代码,手动生成对应训练epoch数的x轴序列:

# Plot the loss
epochs = range(len(r.history['loss']))
plt.plot(epochs, r.history['loss'], label='loss')
plt.legend()
plt.show()

方式2:升级Matplotlib版本

在终端执行以下命令,将Matplotlib更新到支持单参数plot()的版本:

pip install --upgrade matplotlib

内容的提问来源于stack exchange,提问作者Cale McCollough

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:50:28