【问题标题】:tf.keras "history not defined"... but it appears to me to be definedtf.keras“历史未定义”......但在我看来它已被定义
【发布时间】:2021-07-15 12:43:17
【问题描述】:

我正在 TensorFlow 中为我正在学习的入门课程构建一个简单的模型。我找不到错误“历史未定义”的原因。在确定此错误的根源并修复它方面,我将非常感谢任何帮助。

代码如下:

def train_model(model, scaled_train_images, train_labels):
    history = model.fit(scaled_train_images, train_labels, epochs=5, batch_size=256)

# Run function to train the model
train_model(model, scaled_train_images, train_labels)

输出:

Train on 60000 samples

Epoch 1/5
60000/60000 [===] - 56s 936us/sample - loss: 0.0623 - accuracy: 0.9809

Epoch 2/5
60000/60000 [===] - 56s 932us/sample - loss: 0.0538 - accuracy: 0.9838

Epoch 3/5
60000/60000 [===] - 56s 925us/sample - loss: 0.0475 - accuracy: 0.9858

Epoch 4/5
60000/60000 [===] - 55s 923us/sample - loss: 0.0422 - accuracy: 0.9869- los

Epoch 5/5
60000/60000 [===] - 55s 917us/sample - loss: 0.0380 - accuracy: 0.9883

#Load the model history into a pandas DataFrame

frame = pd.DataFrame(history.history)

---------------------------------------------------------------------------
NameError
Traceback (most recent call last)
<ipython-input-22-895ca3f31ddf> in <module>
    1 # Run this cell to load the model history into a pandas DataFrame
    2 
----> 3 frame = pd.DataFrame(history.history)

NameError: name 'history' is not defined

【问题讨论】:

  • 您可能需要先运行所有单元,从第一个开始。每个都构建另一个。
  • 非常好的建议。我已经反复这样做了。每次同样的错误信息。

标签: python pandas dataframe tf.keras


【解决方案1】:

历史变量仅在 train_model 函数内部定义,因此无法在外部访问。

要解决这个问题,请返回:

def train_model(model, scaled_train_images, train_labels):
    return model.fit(scaled_train_images, train_labels, epochs=5, batch_size=256)

history = train_model(model, scaled_train_images, train_labels)

frame = pd.DataFrame(history.history)

【讨论】:

  • 您的解决方案非常直观。我完全按照您在上面写的那样应用它并收到“意外缩进”错误消息。
  • 知道了! history = train_model(...) 都调用定义的函数并将其作为历史可用。 @Matteo,如果没有您的帮助,我将无法解决这个问题。谢谢!
  • @mco 如果它解决了你的问题,记得接受答案:)
猜你喜欢
  • 2021-08-16
  • 2020-04-01
  • 2013-11-05
  • 2018-08-27
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多