簡體   English   中英

如何使用多個 3D 數組訓練回歸 Model?

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

我想用 3D 數組訓練我的回歸 model 嗎? 我該如何在 Python 中做到這一點? 你能指導我嗎? 實際上,我想通過輸入多個 3D arrays 來預測回歸值。 是否可以從多個 3d arrays 中僅預測單個浮點數? 謝謝

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

其中 x1,x2,..xN 是 3D 陣列。 Y 是 output 只是單個浮點數。

關鍵是將您的 3D 樣本重塑為平面一維樣本。 以下示例代碼使用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