从Tensor流模型获得预测

时间:2018-11-27 08:31:02

标签: python python-3.x tensorflow

我想从训练有素的张量流模型中获得预测。以下是我用于训练模型的代码。

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

训练模型后,我想从模型中提取预测。 所以我加了

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

但是运行上面的代码后,我看到以下错误:

  

InvalidArgumentError:必须输入占位符张量“ Y”的值   具有dtype浮点和形状[10 ,?]            [[{{{node Y}} = Placeholderdtype = DT_FLOAT,shape = [10 ,?],_device =“ / job:localhost /副本:0 / task:0 / device:CPU:0”]]

欢迎任何帮助。

1 个答案:

答案 0 :(得分:0)

张量accuracy是张量correct_prediction的函数,而张量Y是其余Y的函数。
因此,您被正确告知您也应该为该占位符提供值。
我假设Y保留着您的标签,因此从直观上来说,您的feed_dict也将包含正确的$url ="https://www.website.com"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 20); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true); curl_setopt($ch, CURLOPT_PROXY, "Proxy:Port"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); $response = curl_exec($ch); 值。
希望有帮助。
祝你好运!