【问题标题】:Tensorflow, what is the best way to add extra inforamtion to a sequential model?Tensorflow,向顺序模型添加额外信息的最佳方法是什么?
【发布时间】:2020-11-02 20:32:56
【问题描述】:

我是机器学习的新手,我正在努力了解如何制作模型。

我想做的事。

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers

# this are my X and Y values
X = np.array([ [x, x+1 ] for x in range(80) ])
Y = [ x + 2 for x in range(80) ]

# The data given in this case is random but has a pridictable pattern.
# if i would use a list of [81,82,1,2] 
# to predict once i fit the model it will give 83.

# I have this extra information that could be helpful for the prediction.
extra_info = [ 1, 2 ]

# What is the best way to add this extra information?

# This is the only way i konw how to add it:
X = np.array([ [x, x+1, extra_info[0], extra_info[1] ] for x in range(80) ])

这是正确的做法吗?

不会混淆模型吗?

如果extra_info 有超过 1000 个字段,这是否也是正确的?

model = keras.Sequential([
  layers.Dense( 64, activation='relu', input_shape =[ 4 ] ),
  layers.Dense( 64, activation='relu' ),
  layers.Dense( 1 )
])

model.compile(
    loss='mse',
    optimizer = tf.keras.optimizers.RMSprop( 0.001 ),
    metrics=['mae', 'mse']
)

history = model.fit(
  X, Y, epochs=20, verbose=0,
)

print(model.predict(np.array([80,81,1,2])))

【问题讨论】:

    标签: python numpy tensorflow keras


    【解决方案1】:

    如果您想要提供给模型的其他信息,您应该查看functional API of Keras。它让您定义额外的输入,而不是合并不同的路径。这允许例如为每个特征创建一个输入路径。

    如果您需要坚持使用顺序 API,这可能是您目前处理它的最佳且唯一的方法。

    【讨论】:

      【解决方案2】:

      这样做时您将面临的问题是 1. 数据存储在 numpy 数组中,而不是张量中,这是模型所期望的输入。要转换它们,您只需使用 tensorflow 方法 convert_to_tensor(查看此文档:https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor)。这看起来像这样:

      X = tf.convert_to_tensor(X)
      Y = tf.convert_to_tensor(Y)
      

      2.这里没有模型可以预测的模式,因为你只是给它随机数,所以它似乎没有学到任何东西。 3.在预测时,您提供的是整个训练数据集,这可能会使事情变得有些混乱。 2&3 真的没有任何问题,只是要记住的事情。除此之外,你做得很好。 希望对您有所帮助!

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2015-03-12
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      相关资源
      最近更新 更多