我正在按照这个教程进行学习: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)))
这里是更大的代码列表:
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 ()
似乎是因为features
是None
,因为你的函数get_features_for_input
没有返回任何内容。
我添加了return features
行,并将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