The key point is to reshape your 3D samples to flat 1D samples. 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).
%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"
Prediction from {inp}, will be:")
print(model.predict(x=inp, batch_size=len(inp), steps=1))
# EOF
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…