2

我試圖導出我的本地張量流模型以在Google Cloud ML上使用它並對其運行預測。我正在關注tensorflow serving example with mnist data。他們處理和使用他們的輸入/輸出向量的方式有很多不同之處,而這並不是您在在線典型示例中找到的。將基本的Tensorflow模型導出到Google Cloud ML

我不能確定如何設置我的簽名的參數:

model_exporter.init(
    sess.graph.as_graph_def(), 
    init_op = init_op, 
    default_graph_signature = exporter.classification_signature(
     input_tensor = "**UNSURE**" , 
     scores_tensor = "**UNSURE**"), 
    named_graph_signatures = { 
     'inputs' : "**UNSURE**", 
     'outputs': "**UNSURE**" 
    } 

    ) 
model_exporter.export(export_path, "**UNSURE**", sess) 

這裏是我的代碼的其餘部分:

import sys 
import tensorflow as tf 
from tensorflow.contrib.session_bundle import exporter 

import numpy as np 
from newpreprocess import create_feature_sets_and_labels 

train_x,train_y,test_x,test_y = create_feature_sets_and_labels() 

x = tf.placeholder('float', [None, 13]) 
y = tf.placeholder('float', [None, 1]) 

n_nodes_hl1 = 20 
n_nodes_hl2 = 20 

n_classes = 1 
batch_size = 100 

def neural_network_model(data): 

    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([13, n_nodes_hl1])), 
         'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} 

    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 
         'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))} 

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])), 
        'biases':tf.Variable(tf.random_normal([n_classes]))} 


    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) 
    l1 = tf.tanh(l1) 

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) 
    l2 = tf.tanh(l2) 

    output = tf.add(tf.matmul(l2, output_layer['weights']), output_layer['biases']) 
    return output 



def train_neural_network(x): 
    output = neural_network_model(x) 
    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(output, y)) 
    optimizer = tf.train.AdamOptimizer(0.003).minimize(cost) 

    hm_epochs = 700 

    with tf.Session() as sess: 
     sess.run(tf.initialize_all_variables()) 

     for epoch in range(hm_epochs): 
      epoch_loss = 0 
      i = 0 
      while i < len(train_x): 
       start = i 
       end = i + batch_size 
       batch_x = np.array(train_x[start:end]) 
     batch_y = np.array(train_y[start:end]) 

     _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, 
               y: batch_y}) 
     epoch_loss += c 
     i+=batch_size 

      print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss/(len(train_x)/batch_size)) 


     prediction = tf.sigmoid(output) 
     predicted_class = tf.greater(prediction,0.5) 
     correct = tf.equal(predicted_class, tf.equal(y,1.0)) 
     accuracy = tf.reduce_mean(tf.cast(correct, 'float')) 

     print('Accuracy:', accuracy.eval({x: test_x, y: test_y})) 

     export_path = "~/Documents/cloudcomputing/Project/RNN_timeseries/" 
     print ("Exporting trained model to %s", %export_path) 
     init_op = tf.group(tf.initialize_all_tables(), name="init_op") 
     saver = tf.train.Saver(sharded = True) 
     model_exporter = exporter.Exporter(saver) 
     model_exporter.init(
      sess.graph.as_graph_def(), 
      init_op = init_op, 
      default_graph_signature = exporter.classification_signature(
       input_tensor = , 
       scores_tensor =), 
      named_graph_signatures = { 
       'inputs' : , 
       'outputs': 
      } 

      ) 
     model_exporter.export(export_path, tf.constant(1), sess) 
     print("Done exporting!") 



train_neural_network(x) 

究竟是上傳和使用在谷歌的步驟Cloud ML?他們的演練似乎是在雲本身而不是本地機器上訓練的模型。

+1

雖然演練演示了雲上的培訓,但您可以按照大多數相同步驟在本地進行培訓,然後部署到雲中。無論哪種情況,您最終都會得到一個包含導出模型的目錄,並且在部署模型時您只需指向該目錄(如果您不使用gcloud,則需要確保將模型複製到GCS)。 – rhaertel80

回答

4

Tensorflow服務和Google Cloud ML是兩回事,不要混淆。 Cloud ML是一個完全託管的解決方案(ML作爲服務),而TF服務則要求您設置和維護您的基礎架構 - 它只是一臺服務器。它們不相關,在輸入/輸出處理方面有不同的要求。

您應遵循的指南是this one。您可以將輸入和輸出添加到集合中,而不是使用圖形簽名。然後在你的代碼的變化將是這樣的:

import sys 
import tensorflow as tf 
from tensorflow.contrib.session_bundle import exporter 

import numpy as np 
from newpreprocess import create_feature_sets_and_labels 
import json 
import os 

train_x,train_y,test_x,test_y = create_feature_sets_and_labels() 

n_nodes_hl1 = 20 
n_nodes_hl2 = 20 
n_classes = 1 
batch_size = 100 

x = tf.placeholder('float', [None, 13]) 
y = tf.placeholder('float', [None, 1]) 
keys_placeholder = tf.placeholder(tf.int64, shape=(None,)) 

keys = tf.identity(keys_placeholder) 

def neural_network_model(data): 
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([13, n_nodes_hl1])), 
         'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} 
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 
         'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))} 
    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])), 
        'biases':tf.Variable(tf.random_normal([n_classes]))} 
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) 
    l1 = tf.tanh(l1) 
    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) 
    l2 = tf.tanh(l2) 
    output = tf.add(tf.matmul(l2, output_layer['weights']), output_layer['biases']) 
    return output 

output = neural_network_model(x) 
prediction = tf.sigmoid(output) 
predicted_class = tf.greater(prediction,0.5) 


inputs = {'key': keys_placeholder.name, 'x': x.name} 
tf.add_to_collection('inputs', json.dumps(inputs)) 

outputs = {'key': keys.name, 
      'prediction': predicted_class.name} 
tf.add_to_collection('outputs', json.dumps(outputs)) 


def train_neural_network(x): 
    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(output, y)) 
    optimizer = tf.train.AdamOptimizer(0.003).minimize(cost) 
    hm_epochs = 700 

    with tf.Session() as sess: 
     sess.run(tf.initialize_all_variables()) 
     for epoch in range(hm_epochs): 
      epoch_loss = 0 
      i = 0 
      while i < len(train_x): 
       start = i 
       end = i + batch_size 
       batch_x = np.array(train_x[start:end]) 
       batch_y = np.array(train_y[start:end]) 

       _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, 
               y: batch_y}) 
       epoch_loss += c 
       i+=batch_size 
      print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss/(len(train_x)/batch_size)) 

     correct = tf.equal(predicted_class, tf.equal(y,1.0)) 
     accuracy = tf.reduce_mean(tf.cast(correct, 'float')) 
     print('Accuracy:', accuracy.eval({x: test_x, y: test_y})) 

     export_path = "~/Documents/cloudcomputing/Project/RNN_timeseries/" 
     print ("Exporting trained model to %s", %export_path) 
     init_op = tf.group(tf.initialize_all_tables(), name="init_op") 

     saver = tf.train.Saver(sharded = True) 
     saver.save(sess, os.path.join(export_path, 'export')) 

     print("Done exporting!") 

train_neural_network(x) 

我有些感動的東西在你的代碼一點點(並沒有實際測試過),但應該給你一個起點。

+0

運行你的代碼後,我獲得了'checkpoint','export.meta'和'export-00000-of-00001'。最後一個是圖形文件還是第一個? –

+0

'export.meta'包含圖形操作和常量的定義,另一個是變量的訓練值。如果你沒有設置「sharder = True」,那麼它沒有數字,但這沒什麼區別。檢查點有點像指針。無論如何,你可以將它們全部上傳到Storage上的存儲桶,並且它將起作用;) –

+0

哦。其實我正在嘗試,但我面對部署部分的錯誤。當我嘗試創建此處提到的版本時:https://cloud.google.com/ml/docs/how-tos/deploying-models-我遇到了一個錯誤:錯誤 對不起,有一個問題。如果您輸入了信息,請檢查並重試。否則,問題可能會自行清除,請稍後再回來查看。 –

相關問題