首页 > 解决方案 > 我正在尝试在 Google Colab 中定义一个函数,但出现此错误:“未定义名称‘train_data’”

问题描述

这是我正在运行的代码,张量流的版本是 2.6.0

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from tensorflow.keras.utils import plot_model
X = tf.range(-100, 100, 4)
y = X + 10
# Split the data into train and test sets
X_train = X[:40] #first 40 are training samples
y_train = y[:40]

X_test = X[40:] # last 10 are testing samples
y_test = y[40:]
y_pred = model.predict(X_test)
def plot_predictions(train_data=X_train,
                     train_labels=y_train,
                     test_data=X_test,
                     test_labels=y_test,
                     peredictions=y_pred):
  '''
  Plots training data, test data and compares predictions to ground truth labels.
  '''
plt.figure(figsize=(10, 7))
# Plot training data in blue
plt.scatter(train_data, train_labels, c="b", labels="Training data")
# Plot testing data in green
plt.scatter(test_data, test_labels, c="g", labels="Testing data")
# Plot model's predictions in red
plt.scatter(test_data, predictions, c="r", labels="predictions")
# Show the legend
plt.legend();

这是我的代码的屏幕截图和 google colab 中的错误:

在此处输入图像描述

标签: pythongoogle-colaboratorytensorflow2.0

解决方案


感谢@MichaelSzczesny,我确实修复了代码。在下面的行之前需要一点空间。是labels="Training data"不正确的,正确的形式是label="Training data"。这是正确且固定的代码:

  plt.figure(figsize=(10, 7))
 # Plot training data in blue
  plt.scatter(train_data, train_labels, c="b", label="Training data")
 # Plot testing data in green
  plt.scatter(test_data, test_labels, c="g", label="Testing data")
 # Plot model's predictions in red
  plt.scatter(test_data, predictions, c="r", label="predictions")
 # Show the legend
  plt.legend();

推荐阅读