def load_keras_classifier(name, path=ASSETS_PATH): """Load a Keras model from disk, as KerasClassifier (sklearn wrapper)""" model_path, classes_path = keras_model_and_classes_paths(name) nn = KerasClassifier(build_fn=do_nothing) # load model and classes nn.model = keras.models.load_model(model_path) classes = pickle.load(open(classes_path, 'rb')) # required for sklearn to believe that the model is trained nn._estimator_type = "classifier" nn.classes_ = classes return nn
layers.Dense(64, activation='relu'), layers.Dropout(0.2), layers.Dense(64, activation='relu'), layers.Dropout(0.2), layers.Dense(10, activation='softmax') ]) model.compile(optimizer=keras.optimizers.SGD(), loss=keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) return model model1 = KerasClassifier(build_fn=mlp_model, epochs=100, verbose=0) model2 = KerasClassifier(build_fn=mlp_model, epochs=100, verbose=0) model3 = KerasClassifier(build_fn=mlp_model, epochs=100, verbose=0) model1._estimator_type = "classifier" model2._estimator_type = "classifier" model3._estimator_type = "classifier" ensemble_clf = VotingClassifier(estimators=[ ('model1', model1), ('model2', model2), ('model3', model3) ], voting='soft') # Hard Voting Classifier:根据少数服从多数来定最终结果; # Soft Voting Classifier:将所有模型预测样本为某一类别的概率的平均值作为标准,概率最高的对应的类型为最终的预测结果; ensemble_clf.fit(x_train, y_train) y_pred = ensemble_clf.predict(x_test) print('acc: ', accuracy_score(y_pred, y_test)) # 9、全部使用 from tensorflow.keras import layers