def test_ensemble(self,test_file):
        assert self.authenticated, 'Not authenticated!'
        
        # download a local copy of the ensemble
        self.logger.info('Creating local ensemble')
        local_ensemble = Ensemble(self.ensemble_res,api=self.api)
        
        # make the Fields object
        source = self.api.get_source(self.source_res)
        fields = Fields(source['object']['fields'])
        
        self.logger.info('Reading test data and generating predictions')
        true_labels = []
        predict_labels = []
        pr = Profile()
        pr.enable()
        with open(test_file) as fid:
            test_reader = csv.reader(fid)
            # skip the header line
            test_reader.next()
            for row in test_reader:
                row_list = [val for val in row]
                true_labels.append(row_list.pop())
                instance = fields.pair(row_list)
                predict_labels.append(local_ensemble.predict(instance,
                                                         by_name=False,
                                                         method=1))

        pr.disable()
        ps = Stats(pr)
        self.predict_time = ps.total_tt
#        eval_args = {'combiner':1}
#        evaluation = self.api.create_evaluation(self.ensemble_res,test_data,eval_args)
#        check_resource(evaluation['resource'],self.api.get_evaluation)   
#        evaluation = self.api.get_evaluation(evaluation['resource'])
#        matrix = evaluation['object']['result']['model']['confusion_matrix']
#        self.predict_time = evaluation['object']['status']['elapsed']/1000
        if self.regression:
            self.results = (predict_labels,true_labels)
        else:
            self.results = make_confusion_matrix(true_labels,predict_labels)
from bigml.ensemble import Ensemble
# Downloads and generates a local version of the ensemble, if it
# hasn't been downloaded previously.
from bigml.api import BigML
ensemble = Ensemble('ensemble/5ddd1a3f1efc925827001f7a',
                    api=BigML("deven96",
                              "81795cceca568fff4115d5c047071728a0700673",
                              domain="bigml.io"))
# To make predictions fill the desired input_data in next line.
input_data = {}
ret = ensemble.predict({'comment_text': "f**k you c**t"}, full=True)
print(ret)
# Requires BigML Python bindings
#
# Install via: pip install bigml
#
# or clone it:
#   git clone https://github.com/bigmlcom/python.git
from bigml.ensemble import Ensemble
# Downloads and generates a local version of the ensemble, if it
# hasn't been downloaded previously.
from bigml.api import BigML
ensemble = Ensemble('ensemble/5cacf3dceba31d30ba000d60',
                    api=BigML("rshelton",
                              "adabd734dd2a2af5cb4e49176f0eb472cfa8ce5a",
                              domain="bigml.io"))
# To make predictions fill the desired input_data in next line.
input_data = {}
ensemble.predict(input_data, full=True)
#
# input_data: dict for the input values
# (e.g. {"petal length": 1, "sepal length": 3})
# full: if set to True, the output will be a dictionary that includes all the
# available information in the predicted node. The attributes vary depending
# on the ensemble type. Please check:
# https://bigml.readthedocs.io/en/latest/#local-ensemble-s-predictions
Exemple #4
0
api = BigML(dev_mode=True)
model = api.get_model("model/563a1c7a3cd25747430023ce")
prediction = api.create_prediction(model, {"petal length": 4.07, "sepal width": 3.15, "petal width": 1.51})

local_model = Model("model/56430eb8636e1c79b0001f90", api=api)
prediction = local_model.predict(
    {"petal length": 0.96, "sepal width": 4.1, "petal width": 2.52}, 2, add_confidence=True, multiple=3
)

local_model = Ensemble("ensemble/564a02d5636e1c79b5006e13", api=api)
local_model = Ensemble("ensemble/564a081bc6c19b6cf3011c60", api=api)
prediction = local_model.predict(
    {"petal length": 0.95, "sepal width": 3.9, "petal width": 1.51, "sepal length": 7.0}, method=2, add_confidence=True
)

local_ensemble = Ensemble("ensemble/564623d4636e1c79b00051f7", api=api)
prediction = local_ensemble.predict({"Price": 5.8, "Grape": "Pinot Grigio", "Country": "Italy", "Rating": 92}, True)

local_anomaly = Anomaly("anomaly/564c5a76636e1c3d52000007", api=api)
prediction = local_anomaly.anomaly_score(
    {"petal length": 4.07, "sepal width": 3.15, "petal width": 1.51, "sepal length": 6.02, "species": "Iris-setosa"},
    True,
)
prediction = local_anomaly.anomaly_score(
    {"petal length": 0.96, "sepal width": 4.1, "petal width": 2.51, "sepal length": 6.02, "species": "Iris-setosa"},
    True,
)
prediction = local_anomaly.anomaly_score({"petal length": 0.96, "sepal width": 4.1, "petal width": 2.51}, True)

api.pprint(prediction)
Exemple #5
0
    def _predict_nba(request, context):
        """

        :param request: iterable sequence of bundled rows
        :return: string
        """
        # Disable caching by uncomment the following two lines
        #md = (('qlik-cache', 'no-store'),)
        #context.send_initial_metadata(md)

        params = []

        # Iterate over bundled rows to retrieve data
        for request_rows in request:
            # Iterate over rows
            for row in request_rows.rows:
                # Retrieve string value of parameter and append to the params variable
                # Length of param is 1 since one column is received, the [0] collects the first value in the list
                param = [d.strData for d in row.duals][0]
                print('param:', param)
                params.append(param)

        print('params:', params)

        # Possible selections to predict
        opt_selections = ['Kevin Durant',
                          'Allen Iverson',
                          'Carmelo Anthony',
                          'Isaiah Thomas',
                          'Cory Jefferson',
                          'Robbie Hummel',
                          'Wesley Johnson']

        # Check selections
        if len(params) == 1 and any([selection in params for selection in opt_selections]):
            selection = params[0].split(' ')  # list of first name and last name
            file = 'NBA_data/Demo_predictPPGPk_{}_{}'.format(selection[0], selection[1])

            with open(file, 'rb') as f:
                data = pickle.load(f)
            print('data:', data)
            correct_res = data['NBA PPG']
            del data['NBA PPG']

            try:
                # Use pre-trained ensemble
                ensemble_link = 'ensemble/5727212049c4a15ca1004b77'
                ensemble = Ensemble(ensemble_link, api=BigML(dev_mode=True, domain='bigml.io'))  # saves locally
            except:
                err = sys.exc_info()
                logging.error('Unexpected error: {}, {}, {}'.format(err[2].tb_frame.f_code.co_filename,
                                                                  err[2].tb_lineno, err[1]))

            # Predict data using the trained ensemble
            res = ensemble.predict(data, with_confidence=True)
            print('res:', res)

            result = 'Predicted number of PPG: {} <br> ' \
                     'Correct number of PPG: {} <br>' \
                     'Confidence: {}'.format(round(res[0], 1), correct_res, round(res[1], 1))
        else:
            result = 'Not possible to predict.'

        # Create an iterable of dual with the result
        duals = iter([SSE.Dual(strData=result)])

        # Yield the row data as bundled rows
        yield SSE.BundledRows(rows=[SSE.Row(duals=duals)])