如何使用多个3D阵列训练回归模型?

2024-03-19 07:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用3D阵列训练我的回归模型?我如何用Python实现它?你能指引我吗。实际上,我想通过输入多个3D数组来预测回归值。是否可以从多个3d阵列中预测单个浮点数?。谢谢

列车型号(x1、x2、x3..xN),y值

其中x1,x2,…xN是三维阵列。 Y是一个浮点数


Tags: 模型数组x1x2型号浮点数列车x3
1条回答
网友
1楼 · 发布于 2024-03-19 07:26:45

关键点是将三维采样重塑为平面1D采样。下面的示例代码使用tf.reshape对输入进行整形,然后将其馈送到规则密集网络,以便回归到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

相关问题 更多 >