【问题标题】:Convert a mix of Pandas/List/Array to something Tensorflow will accept?将 Pandas/List/Array 的组合转换为 Tensorflow 可以接受的东西?
【发布时间】:2019-01-02 22:24:47
【问题描述】:

我正在使用它来将一些数据读入字符级 one-hot 编码。这有点低效,但这是演示代码,因此清晰度比性能更重要:

import tensorflow as tf
sess = tf.Session()

def onehot(str):
    chars = list(map(lambda c: max(0, ord(c) - 48), list(str)))
    twoDim = sess.run(tf.one_hot(chars, 122 - 48))
    # flatten the 2D array:
    return [item for sublist in twoDim for item in sublist]

import pandas
df = pandas.read_csv(sys.argv[1])
train_inputs = df['input'].map(onehot).values
train_labels = df['output'].map(onehot).values

生成的数组打印为[list([0.0, 0.0, 0.0, 0.0, ...

在后面的代码中,我将这些数组输入到 TF 成本优化函数中:

_,cost = sess.run(train_step, feed_dict={x: train_inputs, y_: train_labels})

我在哪里得到这个错误:

ValueError: setting an array element with a sequence.

坦率地说,我对 Python 对类数组数据结构的表示、列表、数组、ndarray、numpy 数组、pandas 数据框等之间的细微差别感到困惑,我不明白我缺少什么。

如何将 train_* 变量转换为 Tensorflow 可接受的类数组结构?

请随时回答可以在未来帮助其他人的清单,或者只是修复我的代码的点答案。

样本数据

这是我的输入 csv 文件的样子:

input,output
abc,def
ghi,jkl
123,456

【问题讨论】:

  • 你的数据是什么样的?
  • 示例数据已添加到问题中。

标签: python pandas numpy tensorflow


【解决方案1】:

添加对 .tolist() 的调用足以让 Tensorflow 接受数据:

train_inputs = df['input'].map(onehot).values.tolist()
train_labels = df['output'].map(onehot).values.tolist()

Tensorflow 喜欢原生数组(用方括号表示),tolist() 输出原生数组,至少对于这个用例来说,与 list() 没有区别。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 2018-09-29
    • 2015-08-09
    • 1970-01-01
    • 2023-03-08
    • 2021-03-30
    相关资源
    最近更新 更多