【问题标题】:cannot unpack non-iterable numpy.float64 object : Keras dataset in Tensorflow 2.0无法解压不可迭代的 numpy.float64 对象:Tensorflow 2.0 中的 Keras 数据集
【发布时间】:2020-10-13 14:09:35
【问题描述】:

我遇到了这个错误,一直不知道如何解决。

我在这句话中遇到了这个错误。

[Loss, Accuracy] = model.evaluate(x_test, y_train)

这是我的完整代码。 我在 keras API 的数据集中尝试使用 IMDB(互联网电影数据库)进行二进制分类。

import tensorflow as tf
import numpy as np
import pandas as pd

from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import SGD, Adam

# Getting Data from imdb
# train_data includes 25000 reviews for movie.
# one element of train_data is list with integer elements, and each integer element is mapped to a certain word
from tensorflow.keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

# Considering 10000 frequently used words
# Making the number of input feature to 10000
# Each unit of input layer means a certain word, and it has 1 when the word is included in a input sentence
def vectorize_sequence(sequences,dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i,sequence] = 1
    return results

x_train = vectorize_sequence(train_data)
x_test = vectorize_sequence(test_data)

y_train = train_labels
y_test = test_labels

model = Sequential()
model.add(Dense(1, input_shape=(10000,), activation='sigmoid'))
model.compile(optimizer=SGD(learning_rate=1e-2), loss='binary_crossentropy')
model.fit(x_train, y_train, epochs=1000)
[Loss, Accuracy] = model.evaluate(x_test, y_train)   # I got the error in here

这是我在 jupyter notebook 中运行上述内容后得到的特定错误消息。

25000/25000 [==============================] - 1s 50us/sample - loss: 2.6755
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-4d3cda640a6a> in <module>
----> 1 [Loss, Accuracy] = model.evaluate(x_test, y_train)

TypeError: cannot unpack non-iterable numpy.float64 object

我应该如何解决这个问题?我应该注意什么来防止该错误?

【问题讨论】:

标签: python keras tensorflow2.0


【解决方案1】:

return_dict=True 添加到model.evaluate() 以查看您有什么,很可能您没有任何指标。像这样:

res_dict = model.evaluate(x_test, y_train, return_dict=True)

查看评估函数的文档:https://www.tensorflow.org/api_docs/python/tf/keras/Model

return_dict

如果为真,损失和度量结果作为字典返回,每个键 是指标的名称。如果为 False,则将它们作为列表返回。

要将指标添加到您的模型,您需要向compile 函数提供一个列表作为metrics 参数:

示例:

model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01),
          loss=tf.keras.losses.CategoricalCrossentropy(),
          metrics=[tf.keras.metrics.CategoricalAccuracy()])

见:https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Metric

您很可能需要tf.keras.metrics.BinaryAccuracy() 指标。

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 2019-06-13
    • 1970-01-01
    • 2020-09-10
    • 2020-01-28
    • 2019-04-22
    • 1970-01-01
    • 2013-05-27
    • 2021-11-01
    相关资源
    最近更新 更多