Java中TensorFlow模型的密集和稀疏张量输入

时间:2017-11-15 22:17:40

标签: java python tensorflow tensorflow-serving

在python&中训练模型后用Java加载它来进行预测,如何为分类输入创建稀疏张量。

我可以成功为数值创建张量:

   Tensor x =
        Tensor.create(
            new long[] {2, 4},
            FloatBuffer.wrap(
                new float[] {
                  6.4f, 3.2f, 4.5f, 1.5f,
                  5.8f, 3.1f, 5.0f, 1.7f
                }));

但对于分类数据,我们需要稀疏张量,我们如何创建呢?

请将我的input_fn()命名为:

def input_fn(df):
  # Creates a dictionary mapping from each continuous feature column name (k) to
  # the values of that column stored in a constant Tensor.
  continuous_cols = {k: tf.constant(df[k].values)
                     for k in CONTINUOUS_COLUMNS}

  # Creates a dictionary mapping from each categorical feature column name (k)
  categorical_cols = {k: tf.SparseTensor(
      indices=[[i, 0] for i in range(df[k].size)],
      values=df[k].values,
      dense_shape=[df[k].size, 1])
                      for k in CATEGORICAL_COLUMNS}

  # Merges the two dictionaries into one.
  feature_cols = dict(continuous_cols.items() + categorical_cols.items())

  # Converts the label column into a constant Tensor.
  label = tf.constant(df[LABEL_COLUMN].values)

  # Returns the feature columns and the label.
  return feature_cols, label

那么,如果我输入如下所示:

age   workclass fnlwgt  education education_num  marital_status occupation      race   LABEL(Income_bracket)
39   State-gov  77516    Bachelors  13          Never-married    Adm-clerical    White    3

如何为连续值和分类值创建张量,并将它们合并为JAVA中Tensorflow的输入。

在python中找到训练模型的代码 - https://gist.github.com/gaganmalhotra/cd6a5898b9caf9005a05c8831a9b9153

@ash

0 个答案:

没有答案