我正在尝试在 Google Colab 中定义一个函数,但出现此错误:“未定义名称‘train_data’”
Posted
技术标签:
【中文标题】我正在尝试在 Google Colab 中定义一个函数,但出现此错误:“未定义名称‘train_data’”【英文标题】:I'm trying to define a function in Google Colab but im getting this error: "name 'train_data' is not defined" 【发布时间】:2021-11-29 00:48:25 【问题描述】:这是我运行的代码,tensorflow的版本是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 中的错误:
【问题讨论】:
您的缩进不正确,您从未调用过该函数。 @MichaelSzczesny 你是什么意思?你的意思是我需要删除空格??但是哪里??你能解释一下吗?? 我不知道你在函数中想要什么。缩进是python语法的一部分。应该在函数内部的所有内容都必须缩进。 知道了,兄弟,谢谢。我只是在“plt.scatter”行之前添加一个空格并修复它。我会再给别人截图 【参考方案1】:感谢@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();
【讨论】:
以上是关于我正在尝试在 Google Colab 中定义一个函数,但出现此错误:“未定义名称‘train_data’”的主要内容,如果未能解决你的问题,请参考以下文章
Google Colab 上的 Tensorflow Tensorboard (Ngrok)
在 Python 中嵌入 Matplotlib 动画(google colab notebook)