使用 TensorFlow 预测新数据

阿罗

由于教程,我正在尝试使用 tensorflow,但我真的在为您必须使用它的方式而苦苦挣扎。

目前我用这些功能训练了一个模型:

def initialize_parameters(beta=0.05):

    tf.set_random_seed(1)

    #Regularization
    if beta!=0:
        regularizer = tf.contrib.layers.l2_regularizer(scale=beta)
    else: regularizer=None

    W1 = tf.get_variable('W1',[4,4,3,8],initializer=tf.contrib.layers.xavier_initializer(seed = 0), regularizer=regularizer)
    W2 = tf.get_variable('W2',[2,2,8,16],initializer=tf.contrib.layers.xavier_initializer(seed = 0), regularizer=regularizer)

    parameters = {"W1": W1,
                  "W2": W2}

    return parameters, regularizer

def forward_propagation(X, parameters, regularizer=None):

    # Retrieve the parameters from the dictionary "parameters" 
    W1 = parameters['W1']
    W2 = parameters['W2']

    # CONV2D: stride of 1, padding 'SAME'
    Z1 = tf.nn.conv2d(X,W1,strides=[1,1,1,1],padding='SAME')
    # RELU
    A1 = tf.nn.relu(Z1)
    # MAXPOOL: window 8x8, sride 8, padding 'SAME'
    P1 = tf.nn.max_pool(A1, ksize=[1,8,8,1], strides=[1,8,8,1],padding='SAME')
    # CONV2D: filters W2, stride 1, padding 'SAME'
    Z2 = tf.nn.conv2d(P1,W2,strides=[1,1,1,1],padding='SAME')
    # RELU
    A2 = tf.nn.relu(Z2)
    # MAXPOOL: window 4x4, stride 4, padding 'SAME'
    P2 = tf.nn.max_pool(A2,ksize=[1,4,4,1],strides=[1,4,4,1],padding='SAME')
    # FLATTEN
    P2 = tf.contrib.layers.flatten(P2)
    # FULLY-CONNECTED without non-linear activation function (not not call softmax).
    # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None" 
    Z3 = tf.contrib.layers.fully_connected(P2, num_outputs=6,activation_fn=None,weights_regularizer=regularizer)
    return Z3

def compute_cost(Z3, Y, regularizer=None):

    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y))


    #Regularize
    if regularizer is not None:
        reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
        reg_term = tf.contrib.layers.apply_regularization(regularizer, reg_variables)
    else:
        reg_term = 0

    cost += reg_term

    return cost

之后,我用我的模型函数调用所有内容:

def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
          num_epochs = 100, minibatch_size = 64, print_cost = True):
    """
    Implements a three-layer ConvNet in Tensorflow:
    CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED

    Arguments:
    X_train -- training set, of shape (None, 64, 64, 3)
    Y_train -- test set, of shape (None, n_y = 6)
    X_test -- training set, of shape (None, 64, 64, 3)
    Y_test -- test set, of shape (None, n_y = 6)
    learning_rate -- learning rate of the optimization
    num_epochs -- number of epochs of the optimization loop
    minibatch_size -- size of a minibatch
    print_cost -- True to print the cost every 100 epochs

    Returns:
    train_accuracy -- real number, accuracy on the train set (X_train)
    test_accuracy -- real number, testing accuracy on the test set (X_test)
    parameters -- parameters learnt by the model. They can then be used to predict.
    """

    ops.reset_default_graph()                         # to be able to rerun the model without overwriting tf variables
    tf.set_random_seed(1)                             # to keep results consistent (tensorflow seed)
    seed = 3                                          # to keep results consistent (numpy seed)
    (m, n_H0, n_W0, n_C0) = X_train.shape             
    n_y = Y_train.shape[1]                            
    costs = []                                        # To keep track of the cost

    # Create Placeholders of the correct shape
    X, Y = tf.placeholder(dtype=tf.float32,shape=(None, n_H0, n_W0, n_C0),name="X"),tf.placeholder(dtype=tf.float32,shape=(None,6),name="Y")

    # Initialize parameters
    parameters = initialize_parameters()

    # Forward propagation: Build the forward propagation in the tensorflow graph
    Z3 = forward_propagation(X, parameters)

    # Cost function: Add cost function to tensorflow graph
    cost = compute_cost(Z3, Y)

    # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost.
    optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)

    # Initialize all the variables globally
    init = tf.global_variables_initializer()

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

        # Run the initialization
        sess.run(init)

        # Do the training loop
        for epoch in range(num_epochs):

            minibatch_cost = 0.
            num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
            seed = seed + 1
            minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)

            for minibatch in minibatches:

                # Select a minibatch
                (minibatch_X, minibatch_Y) = minibatch

                # Run the session to execute the optimizer and the cost, the feedict should contain a minibatch for (X,Y).
                _ , temp_cost = sess.run([optimizer, cost],feed_dict={X:minibatch_X,Y:minibatch_Y})

                minibatch_cost += temp_cost / num_minibatches


            # Print the cost every epoch
            if print_cost == True and epoch % 5 == 0:
                print ("Cost after epoch %i: %f" % (epoch, minibatch_cost))
            if print_cost == True and epoch % 1 == 0:
                costs.append(minibatch_cost)


        # plot the cost
        plt.plot(np.squeeze(costs))
        plt.ylabel('cost')
        plt.xlabel('iterations (per tens)')
        plt.title("Learning rate =" + str(learning_rate))
        plt.show()

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

        # Calculate accuracy on the test set
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
        print(accuracy)
        train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
        test_accuracy = accuracy.eval({X: X_test, Y: Y_test})
        print("Train Accuracy:", train_accuracy)
        print("Test Accuracy:", test_accuracy)

        return train_accuracy, test_accuracy, parameters

到目前为止一切顺利,但我无法根据新数据预测我的模型。目前我已经尝试过这样的事情:

X = scipy.misc.imresize(my_image, size=(64,64)).reshape((1,64,64,3))/255。

with tf.Session() as sess:
    x = tf.placeholder(tf.float32, shape=(None,64, 64, 3))
    z3 = forward_propagation(x, parameters)
    #soft = tf.nn.softmax(z3)
    p = tf.argmax(z3,axis=1)

    #init = tf.global_variables_initializer()
    #sess.run(init)

    prediction = sess.run(p, feed_dict = {x: X})
    print(sess.run(z3, feed_dict = {x: X}))
    print(prediction)

返回错误:尝试使用未初始化的值fully_connected_1/biases [[Node:fully_connected_1/biases/read = IdentityT=DT_FLOAT, _class=["loc:@fully_connected_1/biases"], _device="/job:localhost/replica: 0/任务:0/CPU:0"]]

甚至 :

def predict(X, parameters):
    tf.reset_default_graph()

    W1 = parameters["W1"]
    W2 = parameters["W2"]

    params = {"W1": W1,
              "W2": W2}

    x = tf.placeholder(tf.float32, shape=(None,64, 64, 3))

    z3 = forward_propagation(x, params)
    p = tf.argmax(z3)

    sess = tf.Session()
    prediction = sess.run(p, feed_dict = {x: X})

    return prediction

但是当我用我的图像运行函数时,我有错误Tensor("W1:0", shape=(4, 4, 3, 8), dtype=float32_ref) must be from the same graph as Tensor("Placeholder: 0", 形状=(?, 64, 64, 3), dtype=float32)

我应该如何使用训练有素的模型(我猜我将参数存储在可变参数中?)谢谢

阿罗

好的,这可能不是最好的解决方案,但我是这样做的:

首先我保存图形并将 predict_op 添加到集合中

def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.003,
          num_epochs = 1000, minibatch_size = 64, print_cost = True,beta = 0.05):

... some code that is actually the same than before ...

        saver = tf.train.Saver()
        tf.add_to_collection('predict_op', predict_op)
        saver.save(sess, './my-test-model')

        return train_accuracy, test_accuracy, parameters

然后我加载之前创建的图表

## Predict the classification of the loaded image

## I am using the default data flow graph to run predictions
tf.reset_default_graph()

with tf.Session() as sess:

    ## Load the entire model previuosly saved in a checkpoint
    print("Load the model from path", checkpoint_path)
    the_Saver = tf.train.import_meta_graph(checkpoint_path + '.meta')
    the_Saver.restore(sess, checkpoint_path)

    ## Identify the predictor of the Tensorflow graph
    predict_op = tf.get_collection('predict_op')[0]

    ## Identify the restored Tensorflow graph
    dataFlowGraph = tf.get_default_graph()

    ## Identify the input placeholder to feed the images into as defined in the model 
    x = dataFlowGraph.get_tensor_by_name("X:0")

    ## Predict the image category
    prediction = sess.run(predict_op, feed_dict = {x: my_image_work})

    print("\nThe predicted image class is:", str(np.squeeze(prediction)))

它似乎不是最有效的解决方案,但它有效!如果有更好的方法,请随时分享:)

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

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

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用经过训练的神经网络(Tensorflow 2.0,回归分析)预测新数据?

来自分类Dev

使用 Tensorflow/tflearn 预测金融数据的层

来自分类Dev

使用glm预测新数据

来自分类Dev

tensorflow tf.contrib.learn.SVM 如何重新加载训练好的模型并使用预测对新数据进行分类

来自分类Dev

如何使用Pybrain预测新数据?

来自分类常见问题

使用TensorFlow模型进行预测

来自分类Dev

使用支持向量回归R预测新数据

来自分类Dev

Tensorflow 数据集使用

来自分类Dev

使用Tensorflow做出预测遗失参数

来自分类Dev

使用TensorFlow MNIST进行专家预测

来自分类Dev

使用 tensorflow 的 estimator.DNNRegressor 进行预测

来自分类Dev

使用R中的新x值和多项式回归预测新数据

来自分类Dev

在训练数据标准化后使用sklearn预测新数据

来自分类Dev

如何使用旧数据框中的信息预测新 Python 数据框中列的值

来自分类Dev

如何使用训练好的插入符号对象预测新数据(训练时不使用)?

来自分类Dev

如何使用训练好的插入符号对象预测新数据(训练时不使用)?

来自分类Dev

在R中使用glm和cv.glmnet预测新数据(包括交互和分类变量)

来自分类Dev

向现有模型提供新数据并使用broom :: augment添加预测

来自分类Dev

如何使用经过训练并保存的前馈NN预测新数据

来自分类Dev

我如何使用R中的predict根据新数据集生成一组预测?

来自分类Dev

使用R的新数据进行预测的按子组划分的结果回归

来自分类Dev

MATLAB:使用 fitctree 训练分类器对新数据进行标签预测

来自分类Dev

使用在 R 中训练的神经网络在 C++ 中预测新数据

来自分类Dev

使用tensorflow.js打印预测时出现问题

来自分类Dev

使用现有的Tensorflow模型进行预测的问题

来自分类Dev

尝试使用Tensorflow 2预测SavedModel时出错

来自分类Dev

如何在Tensorflow-keras中使用nlp的预测?

来自分类Dev

在 MNIST 集上使用 TensorFlow 进行预测的困境

来自分类Dev

使用对象检测 tensorflow API 对录制的视频进行预测

Related 相关文章

  1. 1

    如何使用经过训练的神经网络(Tensorflow 2.0,回归分析)预测新数据?

  2. 2

    使用 Tensorflow/tflearn 预测金融数据的层

  3. 3

    使用glm预测新数据

  4. 4

    tensorflow tf.contrib.learn.SVM 如何重新加载训练好的模型并使用预测对新数据进行分类

  5. 5

    如何使用Pybrain预测新数据?

  6. 6

    使用TensorFlow模型进行预测

  7. 7

    使用支持向量回归R预测新数据

  8. 8

    Tensorflow 数据集使用

  9. 9

    使用Tensorflow做出预测遗失参数

  10. 10

    使用TensorFlow MNIST进行专家预测

  11. 11

    使用 tensorflow 的 estimator.DNNRegressor 进行预测

  12. 12

    使用R中的新x值和多项式回归预测新数据

  13. 13

    在训练数据标准化后使用sklearn预测新数据

  14. 14

    如何使用旧数据框中的信息预测新 Python 数据框中列的值

  15. 15

    如何使用训练好的插入符号对象预测新数据(训练时不使用)?

  16. 16

    如何使用训练好的插入符号对象预测新数据(训练时不使用)?

  17. 17

    在R中使用glm和cv.glmnet预测新数据(包括交互和分类变量)

  18. 18

    向现有模型提供新数据并使用broom :: augment添加预测

  19. 19

    如何使用经过训练并保存的前馈NN预测新数据

  20. 20

    我如何使用R中的predict根据新数据集生成一组预测?

  21. 21

    使用R的新数据进行预测的按子组划分的结果回归

  22. 22

    MATLAB:使用 fitctree 训练分类器对新数据进行标签预测

  23. 23

    使用在 R 中训练的神经网络在 C++ 中预测新数据

  24. 24

    使用tensorflow.js打印预测时出现问题

  25. 25

    使用现有的Tensorflow模型进行预测的问题

  26. 26

    尝试使用Tensorflow 2预测SavedModel时出错

  27. 27

    如何在Tensorflow-keras中使用nlp的预测?

  28. 28

    在 MNIST 集上使用 TensorFlow 进行预测的困境

  29. 29

    使用对象检测 tensorflow API 对录制的视频进行预测

热门标签

归档