无法使用TensorFlow Go API进行预测

时间:2017-09-22 15:44:40

标签: go tensorflow

我有一个使用Tensorflow Python API编码的MLP。以下是代码段:

# tf Graph input
x = tf.placeholder("float", [None, 11],name="x")
y = tf.placeholder("float", [None])

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([11, 32], 0, 0.1)),
    'h2': tf.Variable(tf.random_normal([32, 200], 0, 0.1)),
    'out': tf.Variable(tf.random_normal([200, 1], 0, 0.1))
}

biases = {
    'b1': tf.Variable(tf.random_normal([32], 0, 0.1)),
    'b2': tf.Variable(tf.random_normal([200], 0, 0.1)),
    'out': tf.Variable(tf.random_normal([1], 0, 0.1))
}

# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)

    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)

    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

# Construct model
pred = multilayer_perceptron(x, weights, biases)
pred = tf.identity(pred, name="pred")

已使用saved_model_builder.SavedModelBuilder方法训练并保存模型。使用Python API的预测可以使用以下代码完成:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    tf.saved_model.loader.load(sess, ["tag"], "/tmp/saved_models")
    my_pred= sess.graph.get_tensor_by_name('pred:0')
    predictions = sess.run(my_pred, feed_dict={x: pred_data})
    print("The prediction is", predictions)

我正在尝试使用Go API使用以下代码片段进行相同的预测:

df := []float32{9.5,0.0,7.5,0.0,0.0,2.0,0.0,0.0,0.0,0.0,1505292248.0}
 tensor, terr := tf.NewTensor(df) 
 result, runErr := model.Session.Run(
     map[tf.Output]*tf.Tensor{
         model.Graph.Operation("x").Output(0): tensor,
     },
     []tf.Output{
         model.Graph.Operation("pred").Output(0),
     },
     nil,
   )

但是,遇到以下错误:

Error running the session with input, err: In[0] is not a matrix
         [[Node: MatMul = MatMul[T=DT_FLOAT, _output_shapes=[[?,32]], transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_x_0_0, Variable/read)]]

有人可以指出出现此错误的原因吗?

1 个答案:

答案 0 :(得分:0)

错误很明确:In[0] is not a matrix

您的In[0]是:df := []float32{9.5,0.0,7.5,0.0,0.0,2.0,0.0,0.0,0.0,0.0,1505292248.0}

这是一维张量,而不是矩阵。

matmul节点要求其参数都是矩阵,因此需要二维张量。

因此,您必须更改df定义才能定义二维张量,如下所示:

df := [][]float32{{9.5},{0.0},{7.5},{0.0},{0.0},{2.0},{0.0},{0.0},{0.0},{0.0},{1505292248.0}}

关于如何思考/调试tensorflow + go代码的一个很好的参考是:https://pgaleone.eu/tensorflow/go/2017/05/29/understanding-tensorflow-using-go/