python - Tensorflow:使用神经网络对正面或负面短语进行分类

标签 python machine-learning tensorflow neural-network

我正在按照这里的教程进行操作: https://pythonprogramming.net/train-test-tensorflow-deep-learning-tutorial/

我可以训练神经网络并打印出准确度。

但是,我不知道如何使用神经网络进行预测。

这是我的尝试。具体问题是这一行 - 我相信我的问题是我无法将我的输入字符串转换为模型期望的格式:

features = get_features_for_input("This was the best store i've ever seen.")
result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))

这是一个更大的 list :

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) 
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            i = 0
            while i < len(train_x):
                start = i
                end = i + batch_size

                batch_x = np.array(train_x[start:end])
                batch_y = np.array(train_y[start:end])

                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})

                epoch_loss += c 
                i+=batch_size

            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))        
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        print('Accuracy', accuracy.eval({x:test_x, y:test_y}))

        # pos: [1,0] , argmax: 0
        # neg: [0,1] , argmax: 1
        features = get_features_for_input("This was the best store i've ever seen.")
        result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))
        if result[0] == 0:
            print('Positive:',input_data)
        elif result[0] == 1:
            print('Negative:',input_data)

def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros(len(lexicon))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[index_value] += 1

    features = np.array(list(features))

train_neural_network(x)

最佳答案

按照您上面的评论,感觉您的错误 ValueError: Cannot feed value of shape () 是由于 featuresNone,因为您的函数 get_features_for_input 不返回任何内容。

我添加了 return features 行并为特征提供了正确的形状 [1, len(lexicon)] 以匹配占位符的形状。

def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros((1, len(lexicon)))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[0, index_value] += 1

    return features

关于python - Tensorflow:使用神经网络对正面或负面短语进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42950991/

相关文章:

python - 机器学习鸡尾酒会音频应用

tensorflow 密集梯度解释?

python - 使用 TPU 训练 Keras 模型时出现 InternalError

python - 在 Tensorflow 2.0 中通过前辈增加张量的每个元素

python - FileNotFoundError : [Errno 2] No such file or directory google colab

python - 通过链接 str.replace 方法替换字符会产生错误的结果

python - 如何在 python 之外使用 Vowpal Wabbit 模型

python - 为什么 pip install -e 成功后,pip install from github 却失败?

python - 随机森林修剪

machine-learning - 将特征向量矩阵简化为单个有意义的向量