简体   繁体   English

从Tensor Flow Model获得预测

[英]Get a prediction from Tensor Flow Model

I want to get predictions from my trained tensor flow model. 我想从训练有素的张量流模型中获得预测。 The following is the code I have for training my model. 以下是我用于训练模型的代码。

def train_model(self, train, test, learning_rate=0.0001, num_epochs=16, minibatch_size=32, print_cost=True, graph_filename='costs'):

        # Ensure that model can be rerun without overwriting tf variables
        ops.reset_default_graph()
        # For reproducibility
        tf.set_random_seed(42)
        seed = 42
        # Get input and output shapes
        (n_x, m) = train.images.T.shape
        n_y = train.labels.T.shape[0]

        costs = []

        # Create placeholders of shape (n_x, n_y)
        X, Y = self.create_placeholders(n_x, n_y)
        # Initialize parameters
        parameters = self.initialize_parameters()

        # Forward propagation
        Z3 = self.forward_propagation(X, parameters)
        # Cost function
        cost = self.compute_cost(Z3, Y)
        # Backpropagation (using Adam optimizer)
        optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)

        # Initialize variables
        init = tf.global_variables_initializer()

        # Start session to compute Tensorflow graph
        with tf.Session() as sess:

            # Run initialization
            sess.run(init)

            # Training loop
            for epoch in range(num_epochs):

                epoch_cost = 0.
                num_minibatches = int(m / minibatch_size)
                seed = seed + 1

                for i in range(num_minibatches):

                    # Get next batch of training data and labels
                    minibatch_X, minibatch_Y = train.next_batch(minibatch_size)

                    # Execute optimizer and cost function
                    _, minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X.T, Y: minibatch_Y.T})

                    # Update epoch cost
                    epoch_cost += minibatch_cost / num_minibatches

                # Print the cost every epoch
                if print_cost == True:
                    print("Cost after epoch {epoch_num}: {cost}".format(epoch_num=epoch, cost=epoch_cost))
                    costs.append(epoch_cost)

            # Plot costs
            plt.figure(figsize=(16,5))
            plt.plot(np.squeeze(costs), color='#2A688B')
            plt.xlim(0, num_epochs-1)
            plt.ylabel("cost")
            plt.xlabel("iterations")
            plt.title("learning rate = {rate}".format(rate=learning_rate))
            plt.savefig(graph_filename, dpi=300)
            plt.show()

            # Save parameters
            parameters = sess.run(parameters)
            print("Parameters have been trained!")

            # Calculate correct predictions
            correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))

            # Calculate accuracy on test set
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

            print ("Train Accuracy:", accuracy.eval({X: train.images.T, Y: train.labels.T}))
            print ("Test Accuracy:", accuracy.eval({X: test.images.T, Y: test.labels.T}))

        return parameters

After training the model, I want to extract the prediction from the model. 训练模型后,我想从模型中提取预测。 So I add 所以我加

print(sess.run(accuracy, feed_dict={X: test.images.T}))

But I am seeing the below error after running the above code: 但是运行上面的代码后,我看到以下错误:

InvalidArgumentError: You must feed a value for placeholder tensor 'Y' with dtype float and shape [10,?] [[{{node Y}} = Placeholderdtype=DT_FLOAT, shape=[10,?], _device="/job:localhost/replica:0/task:0/device:CPU:0"]] InvalidArgumentError:您必须使用dtype float和形状[10 ,?] [[{{{node Y}} = Placeholderdtype = DT_FLOAT,shape = [10 ,?],_device =“ / job:”输入占位符张量'Y'的值:本地主机/副本:0 /任务:0 /设备:CPU:0“]]

Any help is welcome.. 欢迎任何帮助。

The tensor accuracy is a function of the tensor correct_prediction , which in turn is a function of (among the rest) Y . 张量accuracy是张量correct_prediction的函数,而张量correct_prediction又是(除其他之外) Y的函数。
So you're correctly being told that you should feed values for that placeholder too. 因此,您被正确告知您也应该为该占位符提供值。
I'm assuming Y hold your labels, so it should also make intuitive sense that your feed_dict would also contain the correct Y values. 我假设Y保留了您的标签,因此从直观上来说,您的feed_dict也将包含正确的Y值。
Hope that helps. 希望能有所帮助。
Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM