从Tensor Flow 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

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

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

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

InvalidArgumentError:您必须使用dtype float和形状[10 ,?] [[{{{node Y}} = Placeholderdtype = DT_FLOAT,shape = [10 ,?],_device =“ / job:”输入占位符张量'Y'的值:本地主机/副本:0 /任务:0 /设备:CPU:0“]]

欢迎任何帮助。

ShlomiF

张量accuracy张量的函数,而张量correct_prediction又是(其中的)张量的函数Y
因此,您被正确告知您也应该为该占位符提供值。
我假设Y保留您的标签,因此从直观上来说,您的feed_dict也将包含正确的Y值。
希望能有所帮助。
祝好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Tensor Flow Js中多个时间序列预测的最佳方法

Tensor Flow安装OSX

如何在 Tensor Flow 的再训练示例中打印预测概率?

在Mac上安装Tensor Flow

将 git repo 文件加载到 Tensor flow.load_model() 时出现问题

在R上安装Keras / Tensor Flow

Tensor Flow服务docker无效字段

在Tensor Flow中实施暹罗网络

Tensor Flow是否与Julia 0.6.4兼容?

Python Tensor Flow Training-值错误:Tensor必须与Tensor来自同一图

关于 Tensor Flow 中函数 assign_add() 的困惑

Raspberry Pi安装Tensor-flow和Keras

从Tensor Flow中的文件队列访问文件名

在Tensor Flow中保存和恢复经过培训的LSTM

我用什么代替tensor.dataSync()在tensorflow.js中获得预测值?

Keras Tensor获得名字

Tensorflow:如何从预测Tensor中检索信息?

Powerapps - 无法从 Flow 获得响应

尝试将我的Tensor Flow模型导出到TLITE时出现问题

训练每个后续单词时用于语音识别的Tensor Flow LSTM变慢

用于二进制分类CNN的Tensor Flow Conv1D

在手机上更新Tensor Flow Lite模型而不更新应用程序?

在 Tensor Flow 中训练时这些数字意味着什么

使用Tensor Flow对MNIST手写数字进行CNN训练的振荡精度

遇到以下问题:急切模式不支持build_tensor_flow

为什么使用Tensor Flow keras进行多变量线性回归会导致NaN损失

如何在Tensor Flow 2.0中的Conv2D图层中指定输入形状

从 Keras LSTM 模型转换后无法在 Android 中导入 Tensor flow lite 模型

Keras ImageDataGenerator with flow, Got ValueError: `x` (images tensor) and `y` (labels) should have the same length