简体   繁体   English

如何使用多个 3D 数组训练回归 Model?

[英]How To Train Regression Model With multiple 3D Array?

I want to train my regression model with 3D array?我想用 3D 数组训练我的回归 model 吗? how can I do it in Python?我该如何在 Python 中做到这一点? can you please guide me.你能指导我吗? Actually I want to predict regression value from giving input of multiple 3D arrays.实际上,我想通过输入多个 3D arrays 来预测回归值。 Is it possible to predict just single float number from multiple 3d arrays?.是否可以从多个 3d arrays 中仅预测单个浮点数? Thanks谢谢

train.model((x1,x2,x3..xN), y-value). train.model((x1,x2,x3..xN), y 值)。

where x1,x2,..xN are 3D array.其中 x1,x2,..xN 是 3D 阵列。 and Y is output just single float number. Y 是 output 只是单个浮点数。

The key point is to reshape your 3D samples to flat 1D samples.关键是将您的 3D 样本重塑为平面一维样本。 The following example code uses tf.reshape to reshape input before feeding to a regular dense network for regression to a single value output by tf.identity (no activation).以下示例代码使用tf.reshape对输入进行整形,然后将其馈送到常规密集网络以通过 tf.identity 回归到单个值tf.identity (未激活)。

%tensorflow_version 2.x
%reset -f

import tensorflow as tf
from   tensorflow.keras import *
from   tensorflow.keras.models import *
from   tensorflow.keras.layers import *
from   tensorflow.keras.callbacks import *

class regression_model(Model):
    def __init__(self):
        super(regression_model,self).__init__()
        self.dense1 = Dense(units=300, activation=tf.keras.activations.relu)
        self.dense2 = Dense(units=200, activation=tf.keras.activations.relu)
        self.dense3 = Dense(units=1,   activation=tf.identity)

    @tf.function
    def call(self,x):
        h1 = self.dense1(x)
        h2 = self.dense2(h1)
        u  = self.dense3(h2) # Output
        return u

if __name__=="__main__":
    inp = [[[1],[2],[3],[4]], [[3],[3],[3],[3]]] # 2 samples of whatever shape
    exp = [[10],              [12]] # Regress to sums for example'

    inp = tf.constant(inp,dtype=tf.float32)
    exp = tf.constant(exp,dtype=tf.float32)

    NUM_SAMPLES = 2
    NUM_VALUES_IN_1SAMPLE = 4
    inp = tf.reshape(inp,(NUM_SAMPLES,NUM_VALUES_IN_1SAMPLE))

    model = regression_model()
    model.compile(loss=tf.losses.MeanSquaredError(),
                  optimizer=tf.optimizers.Adam(1e-3))
    
    model.fit(x=inp,y=exp, batch_size=len(inp), epochs=100)

    print(f"\nPrediction from {inp}, will be:")
    print(model.predict(x=inp, batch_size=len(inp), steps=1))
# EOF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM