初始化和使用tf.占位符(tf.字符串),向其输入值,并在必要时将其转换回字符串

2024-06-26 14:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在tensorflow中实现一个模型时遇到了困难。 我想编程一个预测情绪极性的模型。要做到这一点,我首先要训练模型。这就是发生错误的地方。在

我使用了三个变量:句子(或情绪)、目标(句子中极性适用的单词)和极性本身。前两个变量是字符串,极性是一个向量(正时为[1,0,0],负时为[0,0,1])。在

为了使这些变量tf.占位符(tf.字符串). 当我运行这个模型时,我得到了以下错误:“您必须用dtype string为占位符张量‘placeholder_1’输入一个值”

当我想对语句变量进行操作时,我也会遇到一个问题:我需要将句子拆分成单词,但是由于句子是一个占位符,我首先必须将它转换回字符串。在

该模型的输入是三个向量:sVec(所有句子的字符串向量)、tVec(所有目标的字符串向量)和pVec(所有极性向量作为向量)

我处理这个错误已经有一段时间了,所以任何帮助都是非常感谢的。下面是代码。提前谢谢。在

polarity = tf.placeholder(tf.float32, shape=[1, c_cardi])#label
sentence = tf.placeholder(tf.string)  #inputdata
target = tf.placeholder(tf.string)

def multilayer_perceptron(mi, target, weights, biases):
    # This method works correctly


def modelA(sentence, target):
    # The error might refer to this:
    sess2 = tf.Session()
    sentence = sess2.run(sentence) # I need to get the value of the tensor here
    sess2.close()
    words = sentence.split()
    # Code goes on, no error here
    return prediction


def trainModelA(sVec, tVec, pVec):
    prediction = modelA(sentence, target)
    cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=polarity))
    optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost_function)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(epochs):
            # The error might refer to this part
            sess.run(optimizer, feed_dict={sentence:sVec, target: tVec, polarity:pVec})
            # Code goes on

trainModelA(sVec, tVec, pVec)

编辑:

在我看来,错误发生在以下行:sentence=sess2.run(sentence)。因为我运行modelA(sentence,target),所以我有一个句子作为输入,但它还没有被值填充。然而,这似乎是一种方式,所以我仍然不知道发生了什么。在


Tags: run字符串模型targettf错误向量sentence