问题
I need to build a model that based on the classification output selects one model for regression. In my example, there are 3 independent Regressors and 1 classifier. The Regressor model is selected based upon the previous classification.
I would like to get an integrated model so I can compile it and use the interpreter of the tensorflow Lite in Android.
In this example I get the class in y_class and select the model models[ y_class ] to finally make the prediction (regression).
y_prob= clf.predict(test)
y_class = y_prob.argmax(axis=-1)[0]
y_regress = models[ y_class ].predict(test)
I would like and integrated model to be able to get the y_regress directly.
import pandas as pd
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model
from keras import optimizers
import tensorflow.keras.backend as K
import keras
df = pd.read_csv('https://www.dropbox.com/s/jc36fdgmi43iy41/tflitetest.csv?dl=1')
df = df.iloc[:,1:]
X = df.iloc[:,0:12] #data
y = df.iloc[:,12:14] # Values for regression
f = df.f # 3 classes
#building the classifier
inputx = Input(shape=(12,))
x = Dense(30, activation='sigmoid')(inputx)
floor = Dense(3, activation='softmax')(x)
clf = Model(inputs=inputx,output=floor)
clf.compile(
optimizer=keras.optimizers.Adadelta(),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'])
clf.fit(X,f,epochs=200)
#building 3 independent Regressors
models = {}
for i in range(3):
x = Dense(30, activation='sigmoid')(inputx)
x = Dense(100, activation='sigmoid')(x)
y1y2 = Dense(2)(x)
models[i]= Model(inputs=inputx,output=y1y2)
models[i].compile(
optimizer='adam',
loss='mean_squared_error',
metrics=['accuracy'])
models[i].fit(X[ f==i] , y[f==i] ,epochs=200)
test = X.iloc[-1].values.reshape((1,-1))
y_prob= clf.predict(test)
y_class = y_prob.argmax(axis=-1)[0]
y_regress = models[ y_class ].predict(test)
print(y_regress)
来源:https://stackoverflow.com/questions/57355199/build-a-model-with-keras-functional-api-for-tensorflow-lite-merge-one-classifie