首页 > 解决方案 > 如何在 Tensorflow 中获得 LSTM 的测试准确度

问题描述

我正在尝试在经过训练的算法上测试我的测试集并打印测试的准确性。

我的数据是机器数据,我已经尝试了所有我可以在网上找到的用于计算和打印我的测试准确性的解决方案。我正在使用 TensorFlow 1.13。和虚拟机上的 Python 3。我从 python programming.net 获得了代码,并为我的数据修改了它。

import tensorflow as tf
from sklearn.metrics import  recall_score, precision_score
from tensorflow.contrib.learn.python.learn.estimators._sklearn
import accuracy_score
from tensorflow.contrib.metrics import f1_score
from tensorflow.python import keras
from tensorflow.python.ops import rnn, rnn_cell
from DataPreprocessing import x_train, x_test, y_train, y_test
import numpy as np

hm_epochs = 30
n_classes = 328 
batch_size = int (8)
chunk_size = 3
n_chunks = 8
rnn_size = 128
size=len(x_train)
learning_rate=0.001
length=len(x_train)


x =  tf.compat.v1.placeholder(tf.float32, [None, n_chunks,    chunk_size])
y =  tf.compat.v1.placeholder(tf.float32)

def recurrent_neural_network(x):
    layer =    {'weights':tf.Variable(tf.random.normal([rnn_size,n_classes])),
         'biases':tf.Variable(tf.random.normal([n_classes]))}


    x = tf.transpose(x, [1,0,2])
    x = tf.reshape(x, [-1, chunk_size])
    x = tf.split(x, n_chunks, axis=0)


    lstm_cell = tf.keras.layers.LSTMCell(rnn_size)
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)

    output = tf.matmul(outputs[-1],layer['weights']) + layer['biases']

    return output

def lstm_neural_network(x):
    prediction = recurrent_neural_network(x)
    cost = tf.reduce_mean(tf.compat.v1.losses.mean_squared_error(prediction, y))
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)


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

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for i in range(int(length / batch_size)):
                start=i
                end=i+batch_size
                epoch_x = np.array(x_train[start:end])
                epoch_y = np.array(y_train[start:end])
                epoch_x = np.reshape(epoch_x, [-1, n_chunks, chunk_size])
                i, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y},)
                epoch_loss += c
                i=end
            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(prediction, feed_dict={x:x_test, y:y_test}))

lstm_neural_network(x)

最后 4 行是问题所在,因为其余行都很好。

它显示的错误是:TypeError: eval() got multiple values for argument 'feed_dict'

标签: pythonpython-3.xtensorflow

解决方案


y =  tf.compat.v1.placeholder(tf.float32)

def recurrent_neural_network(x):
    layer =    {'weights':tf.Variable(tf.random.normal([rnn_size,n_classes])),
         'biases':tf.Variable(tf.random.normal([n_classes]))}


x = tf.transpose(x, [1,0,2])
x = tf.reshape(x, [-1, chunk_size])
x = tf.split(x, n_chunks, axis=0)


lstm_cell = tf.keras.layers.LSTMCell(rnn_size)
outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)

output = tf.matmul(outputs[-1],layer['weights']) + layer['biases']

return output

def lstm_neural_network(x):
    prediction = recurrent_neural_network(x)
    cost = tf.reduce_mean(tf.compat.v1.losses.mean_squared_error(prediction, y))
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)

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

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for i in range(int(length / batch_size)):
            start=i
            end=i+batch_size
            epoch_x = np.array(x_train[start:end])
            epoch_y = np.array(y_train[start:end])
            epoch_x = np.reshape(epoch_x, [-1, n_chunks, chunk_size])
            i, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y},)
            epoch_loss += c
            i=end
        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('Acc

推荐阅读