无法解压缩Tensorflow 2.0中不可编辑的numpy.float64对象:Keras数据集

2024-04-25 22:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我犯了这个错误,一直不知道如何解决它

我在这句话里犯了这个错误

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

这是我的全部代码。 我在KerasAPI的数据集中尝试使用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笔记本上运行上述内容后得到的具体错误消息

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

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


Tags: infromtestimportinputdatalabelsmodel
1条回答
网友
1楼 · 发布于 2024-04-25 22:32:02

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

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

请参阅evaluate函数的文档:https://www.tensorflow.org/api_docs/python/tf/keras/Model

return_dict

If True, loss and metric results are returned as a dict, with each key being the name of the metric. If False, they are returned as a list.

要将度量添加到模型中,需要为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()度量

相关问题 更多 >

    热门问题