TensorFlow中model.fit()报错ValueError:无法识别list类型数据怎么办?
问题
我尝试运行CS50's AI课程的如下代码:
import csv import tensorflow as tf from sklearn.model_selection import train_test_split # Read data in from file with open("banknotes.csv") as f: reader = csv.reader(f) next(reader) data = [] for row in reader: data.append( { "evidence": [float(cell) for cell in row[:4]], "label": 1 if row[4] == "0" else 0, } ) # Separate data into training and testing groups evidence = [row["evidence"] for row in data] labels = [row["label"] for row in data] X_training, X_testing, y_training, y_testing = train_test_split( evidence, labels, test_size=0.4 ) # Create a neural network model = tf.keras.models.Sequential() # Add a hidden layer with 8 units, with ReLU activation model.add(tf.keras.layers.Dense(8, input_shape=(4,), activation="relu")) # Add output layer with 1 unit, with sigmoid activation model.add(tf.keras.layers.Dense(1, activation="sigmoid")) # Train neural network model.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"] ) model.fit(X_training, y_training, epochs=20) # Evaluate how well model performs model.evaluate(X_testing, y_testing, verbose=2)
但出现如下错误:
Traceback (most recent call last): File "C:\Users\Eric\Desktop\coding\cs50\ai\lectures\lecture5\banknotes\banknotes.py", line 41, in <module> model.fit(X_training, y_training, epochs=20) File "C:\Users\Eric\Desktop\coding\cs50\ai\.venv\Lib\site-packages\keras\src\utils\traceback_utils.py", line 122, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Eric\Desktop\coding\cs50\ai\.venv\Lib\site-packages\keras\src\trainers\data_adapters\__init__.py", line 113, in get_data_adapter raise ValueError(f"Unrecognized data type: x={x} (of type {type(x)})") ValueError: Unrecognized data type: x=[...] (of type <class 'list'>)
我使用Windows电脑,Python版本3.11.8,TensorFlow版本2.16.1。相同代码在Google Colab可正常运行,期望输出如下:
Epoch 1/20 26/26 [==============================] - 1s 2ms/step - loss: 1.1008 - accuracy: 0.5055 Epoch 2/20 26/26 [==============================] - 0s 2ms/step - loss: 0.8588 - accuracy: 0.5334 Epoch 3/20 26/26 [==============================] - 0s 2ms/step - loss: 0.6946 - accuracy: 0.5917 Epoch 4/20 26/26 [==============================] - 0s 2ms/step - loss: 0.5970 - accuracy: 0.6683 Epoch 5/20 26/26 [==============================] - 0s 2ms/step - loss: 0.5265 - accuracy: 0.7120 Epoch 6/20 26/26 [==============================] - 0s 2ms/step - loss: 0.4717 - accuracy: 0.7655 Epoch 7/20 26/26 [==============================] - 0s 2ms/step - loss: 0.4258 - accuracy: 0.8177 Epoch 8/20 26/26 [==============================] - 0s 2ms/step - loss: 0.3861 - accuracy: 0.8433 Epoch 9/20 26/26 [==============================] - 0s 2ms/step - loss: 0.3521 - accuracy: 0.8615 Epoch 10/20 26/26 [==============================] - 0s 2ms/step - loss: 0.3226 - accuracy: 0.8870 Epoch 11/20 26/26 [==============================] - 0s 2ms/step - loss: 0.2960 - accuracy: 0.9028 Epoch 12/20 26/26 [==============================] - 0s 2ms/step - loss: 0.2722 - accuracy: 0.9125 Epoch 13/20 26/26 [==============================] - 0s 2ms/step - loss: 0.2506 - accuracy: 0.9283 Epoch 14/20 26/26 [==============================] - 0s 2ms/step - loss: 0.2306 - accuracy: 0.9514 Epoch 15/20 26/26 [==============================] - 0s 3ms/step - loss: 0.2124 - accuracy: 0.9660 Epoch 16/20 26/26 [==============================] - 0s 2ms/step - loss: 0.1961 - accuracy: 0.9769 Epoch 17/20 26/26 [==============================] - 0s 2ms/step - loss: 0.1813 - accuracy: 0.9781 Epoch 18/20 26/26 [==============================] - 0s 2ms/step - loss: 0.1681 - accuracy: 0.9793 Epoch 19/20 26/26 [==============================] - 0s 2ms/step - loss: 0.1562 - accuracy: 0.9793 Epoch 20/20 26/26 [==============================] - 0s 2ms/step - loss: 0.1452 - accuracy: 0.9830 18/18 - 0s - loss: 0.1407 - accuracy: 0.9891 - 187ms/epoch - 10ms/step [0.14066053926944733, 0.9890710115432739]
问题原因与解决方法
原因
TensorFlow 2.16.1(较新版本)对输入数据类型的要求更严格,不再直接支持Python原生列表作为model.fit()的输入;而Google Colab使用的TensorFlow版本通常较低,仍兼容列表输入。
解决方法
将训练和测试数据转换为NumPy数组或TensorFlow张量即可解决问题,具体有两种实现方式:
方式1:使用NumPy转换
在导入模块时添加import numpy as np,然后将分割后的数据集转换为数组:
import csv import tensorflow as tf import numpy as np # 新增导入 from sklearn.model_selection import train_test_split # ... 读取数据的代码保持不变 ... # Separate data into training and testing groups evidence = [row["evidence"] for row in data] labels = [row["label"] for row in data] X_training, X_testing, y_training, y_testing = train_test_split( evidence, labels, test_size=0.4 ) # 转换为NumPy数组 X_training = np.array(X_training) X_testing = np.array(X_testing) y_training = np.array(y_training) y_testing = np.array(y_testing) # ... 后续创建模型、编译、训练、评估的代码保持不变 ...
方式2:使用TensorFlow转换
直接用tf.convert_to_tensor()将列表转为张量:
# 转换为TensorFlow张量 X_training = tf.convert_to_tensor(X_training, dtype=tf.float32) X_testing = tf.convert_to_tensor(X_testing, dtype=tf.float32) y_training = tf.convert_to_tensor(y_training, dtype=tf.float32) y_testing = tf.convert_to_tensor(y_testing, dtype=tf.float32)
说明
两种方式都能让TensorFlow正确识别输入数据类型,运行后即可得到期望的训练和评估输出。
内容的提问来源于stack exchange,提问作者Eric Vo
相关产品推荐
相关产品推荐

