将pandas DataFrame传入tf.convert_to_tensor()时遇Unsupported object type int错误
将Pandas DataFrame转为Tensor时出现
Unsupported object type int错误 我在调用tensorflow.convert_to_tensor()传入Pandas DataFrame时,一直收到Unsupported object type int错误。我已经把所有列都转成了TensorFlow支持的类型,但问题还是没解决。
以下是DataFrame的信息:
<class 'pandas.core.frame.DataFrame'> RangeIndex: 783 entries, 0 to 782 Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 gearbox 783 non-null string 1 fuel 783 non-null string 2 body_type 783 non-null string 3 sports_package 783 non-null int32 4 mileage 783 non-null int32 5 registration_month 783 non-null int32 6 registration_year 783 non-null int32 7 zip_code 783 non-null int32 8 horsepower 783 non-null int32 9 carplay 783 non-null int32 10 accident_free 783 non-null int32 dtypes: int32(8), string(3) memory usage: 42.9 KB None
完整报错信息:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[146], line 19 13 x['accident_free'] = x['accident_free'].astype('int32') 17 print(x.info()) ---> 19 tf.convert_to_tensor(x) 21 model.fit(x, y) File ~/miniforge3/envs/tf_projects/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs) 151 except Exception as e: 152 filtered_tb = _process_traceback_frames(e.__traceback__) --> 153 raise e.with_traceback(filtered_tb) from None 154 finally: 155 del filtered_tb File ~/miniforge3/envs/tf_projects/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py:98, in convert_to_eager_tensor(value, ctx, dtype) 96 dtype = dtypes.as_dtype(dtype).as_datatype_enum 97 ctx.ensure_initialized() ---> 98 return ops.EagerTensor(value, ctx.device_name, dtype) ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).
更新:DataFrame部分内容:
gearbox fuel body_type sports_package mileage registration_month 0 manual petrol hatchback 0 26025 12 1 manual petrol hatchback 0 22987 11 2 manual petrol hatchback 0 13513 12 registration_year zip_code horsepower carplay accident_free 0 2021 86470 90 1 0 1 2021 78628 90 0 1 2 2021 14641 90 1 0
解决方法
1. 处理字符串类型列
TensorFlow无法直接解析Pandas的string dtype列,必须先对类别型字符串做编码处理:
- 独热编码(适合无顺序的类别):
x_encoded = pd.get_dummies(x, columns=['gearbox', 'fuel', 'body_type'])
- 标签编码(适合有顺序的类别):
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() for col in ['gearbox', 'fuel', 'body_type']: x[col] = le.fit_transform(x[col])
2. 转NumPy数组后再生成Tensor
处理完字符串列后,建议先将DataFrame转为NumPy数组,再传入tf.convert_to_tensor():
import numpy as np x_tensor = tf.convert_to_tensor(x_encoded.values.astype(np.int32))
3. 强制统一数值列类型
部分int32列可能实际存储的是Python原生int对象而非NumPy int32,需强制转换:
import numpy as np for col in x.select_dtypes(include=['int32']).columns: x[col] = x[col].astype(np.int32)
4. 直接用TensorFlow数据集加载(推荐)
如果是为了模型训练,无需手动转Tensor,直接用tf.data.Dataset构建输入:
dataset = tf.data.Dataset.from_tensor_slices((dict(x), y))
内容的提问来源于stack exchange,提问作者Daniel Becker
相关产品推荐
相关产品推荐

