【问题标题】:Tensorflow - use string labels to train neural networkTensorflow - 使用字符串标签训练神经网络
【发布时间】:2020-01-08 16:59:37
【问题描述】:

对于一个大学项目,我必须使用 Tensorflow 为 OCR 任务实现一个神经网络。 训练数据集包含两个文件,train-data.csvtrain-target.csv。 在 train-data 文件中,每一行都用 16x8 位图的位填充,在 train-target 文件中,每一行都是一个字符 [az],它是对应的标签train-data 中的行。

我在使用标签数据集时遇到了一些问题,我已经按照 MNIST 数据集的教程进行操作,但这里的区别在于我使用的是字符串标签而不是一次性编码向量。 按照教程,我正在尝试使用 softmax 函数和交叉熵。

# First y * tf.log(y_hat) computes the element-wise multiplication of the two resulting vectors

# Second, tf.reduce_sum( , reduction_indices=[1]) computes the sum along the second dimension (the first one are the examples)
# Finally, tf.reduce_mean() computes the mean over the first dimension, i.e. the examples
cross_entropy = tf.reduce_mean(-tf.reduce_sum(tf.strings.to_number(y) * tf.math.log(y_hat), reduction_indices=[1]))

train_step = tf.compat.v1.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

在上面的行中,我使用 tf.strings.to_number(y) 将 char 转换为数值。

当我运行会话时,这种转换会导致问题,因为 run() 方法不接受张量对象。

for _ in range(1000):
    batch_xs, batch_ys = next_batch(100, raw_train_data, train_targets)
    sess.run(train_step, feed_dict={x: batch_xs, y: tf.strings.to_number(batch_ys.reshape((100,1)))})

如果我不将 char 转换为数值,则会收到此错误:

InvalidArgumentError: StringToNumberOp could not correctly convert string: e
 [[{{node StringToNumber}}]]

我正试图弄清楚如何解决这个问题或如何使用字符标签训练神经网络,我整天都在研究这个问题。 有谁知道如何解决这个问题?

【问题讨论】:

    标签: python tensorflow neural-network


    【解决方案1】:

    我终于找到了错误。 因为我对机器学习很陌生,所以我忘记了许多算法不处理分类数据集。

    解决方案是对目标标签执行 one-hot 编码,并使用此函数将此新数组提供给 newtork:

    # define universe of possible input values
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    
    # define a mapping of chars to integers
    char_to_int = dict((c, i) for i, c in enumerate(alphabet))
    int_to_char = dict((i, c) for i, c in enumerate(alphabet))
    
    
    def one_hot_encode(data_array):
        integer_encoded = [char_to_int[char] for char in data_array]
    
        # one hot encode
        onehot_encoded = list()
        for value in integer_encoded:
            letter = [0 for _ in range(len(alphabet))]
            letter[value] = 1
            onehot_encoded.append(letter)
    
        return onehot_encoded
    

    【讨论】:

    • 这有一个缺陷,因为 tensorflow 不能预测输出中的数字,我必须再次将这些数字映射到字母表中。
    猜你喜欢
    • 2017-05-23
    • 2020-04-28
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多