【问题标题】:can not convert pandas numpy column into tensors无法将 pandas numpy 列转换为张量
【发布时间】:2021-06-02 14:41:03
【问题描述】:

我正在尝试将我的一列转换为张量,但它给了我一个错误。但是如果我尝试自己转换数组,我不会有问题。

例如这有效:

dummy_array = [np.array([0.1, 0.2]), np.array([0.3, 0.4]), np.array([0.5, 0.6]), np.array([0.7, 0.8]), np.array([0.9, 0.11])]

tf.convert_to_tensor((dummy_array))

但这不是:

sample_df = pd.DataFrame()
sample_df['id'] = [1,2,3,4,5]
sample_df['x'] = dummy_array
sample_df['y'] = np.random.randint(0,2,size=5)
sample_df['x'] = sample_df['x'].apply(lambda x: x.astype('float32'))
tf.convert_to_tensor(sample_df['x'])

我得到的错误是:

 Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

我想把它保存在数据框中,这样我就可以进行训练、验证、测试拆分

【问题讨论】:

标签: tensorflow keras tensorflow2.0 numpy-ndarray tf.keras


【解决方案1】:

在将 Pandas 数据帧转换为张量之前,将数据帧列转换为列表。

找到下面的工作示例。

import tensorflow as tf
import pandas as pd
import numpy as np
sample_df = pd.DataFrame()
sample_df['id'] = [1,2,3,4,5]
dummy_array = [np.array([0.1, 0.2]), np.array([0.3, 0.4]), np.array([0.5, 0.6]), np.array([0.7, 0.8]), np.array([0.9, 0.11])]
sample_df['x'] = dummy_array
sample_df['y'] = np.random.randint(0,2,size=5)
sample_df['x'] = sample_df['x'].apply(lambda x: x.astype('float32'))
tf.convert_to_tensor(sample_df['x'].to_list())

输出

<tf.Tensor: shape=(5, 2), dtype=float32, numpy=
array([[0.1 , 0.2 ],
       [0.3 , 0.4 ],
       [0.5 , 0.6 ],
       [0.7 , 0.8 ],
       [0.9 , 0.11]], dtype=float32)>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多