【问题标题】:TensorFlow- From Object to String/IntTensorFlow-从对象到字符串/整数
【发布时间】:2021-11-28 15:51:03
【问题描述】:

假设当使用pd.read_csv(file_path) 读取特定的df 时,使用object dtype 列而不是string/int32 dtype 列读取文件。

这表示尝试将 pandas df 转换为 tensorflow df 时出现问题:

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

# convert dummy data to object to reproduce the problem
d={'A':['a', 'b', 'c', 'd'], 'B':['e', 'f', 'g', 'h'], 'number':[1, 2, 3, 4]}
df=pd.DataFrame(d).astype(object)

# converting df to tf.dataset
ds = tf.data.Dataset.from_tensor_slices(dict(df))

出现下一个错误:

ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型 int)。

如何正确处理对象 dtype 列到字符串/数字列?

想法是得到下一个输出:

ds
# console output
<TensorSliceDataset shapes: {A: (), B: (), number: ()}, types: {A: tf.string, B: tf.string, number: tf.int64}>

【问题讨论】:

    标签: python pandas dataframe tensorflow


    【解决方案1】:

    试试:

    df = pd.DataFrame(d).astype('category')
    df['number'] = df['number'].astype(int)
    
    ds = tf.data.Dataset.from_tensor_slices(dict(df))
    
    <TensorSliceDataset shapes: {A: (), B: (), number: ()}, types: 
           {A: tf.string, B: tf.string, number: tf.int32}>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      相关资源
      最近更新 更多