简体   繁体   中英

Load multiple saved machine learning models with relative features sets in pythonic way

I have a directory structure on my laptop as shown.

/Directory 1. file1.model 2. file2.model 3. file3.model

/Directory2 1. features1.csv 2. features2.csv 3. features3.csv

`def LoadModelFiles(self):
     model1 = Directory/file1.model
     model2 = Directory/file2.model
     model3 = Directory/file3.model
   return model1,model2, model3

 def LoadFeaturesets(self):
     feature_set1 = Directory/features1.csv
     feature_set2 = Directory/features2.csv
     feature_set3 = Directory/feature3.csv
    return feature_set1,feature_set2,feature_set3

 def Classifier(self):
     model1,model2,model3 = self.LoadModelFiles()
     set1, set2, set3 = self.LoadFeaturesets()

    pred1 = model1.predict(feature1)
    pred2 = model2.predict(feature2)
    pred3 = model3.predict(feature3)

  return pred1, pred2, pred3`

what if I have multiple file. The above code is bad as I am new to python.

I want to load them into different variable, so I wrote the code as shown. I can use those model variables to pass different set of feature stored in those csv files.

So even in Classifier method I have to write 3 prediction statements, what if I have N number of models with relative feature set.

Can we write a pythonic or few lines of code to eliminate duplicated lines and load the files.

Added thing is I am writing a web service where 1st model predictions(based on its predictions) invokes the next models.

Currently I have 15 model files. Where 1st model file invokes the next 14 files.

Thanks in advance.

def load_model(model_path):
    pass

def load_feature(feature_path):
    pass

def predict(idx):
    model = load_model('Directory/file{}.model'.format(idx))
    features = load_feature('Directory/feature{}.csv'.format(idx))
    return model.predict(features)

predictions = [predict(i) for i in range(n)]

Hope this would help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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