ScikitLearn model giving 'LocalOutlierFactor&#

2019-06-08 00:45发布

I'm new to machine learning world and I have built and trained a ml model using ScikitLearn library.It works perfectly well in the Jupyter notebook but when I deployed this model to Google Cloud ML and try to serve it using a Python script, it throws an error.

Here's a snippet from my model code:

Updated:

from sklearn.metrics import classification_report, accuracy_score
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor

# define a random state
state = 1

classifiers = {
    "Isolation Forest": IsolationForest(max_samples=len(X),
                                       contamination=outlier_fraction,
                                       random_state=state),
    # "Local Outlier Factor": LocalOutlierFactor(
    # n_neighbors = 20,
    # contamination = outlier_fraction)
}

import pickle
# fit the model
n_outliers = len(Fraud)

for i, (clf_name, clf) in enumerate(classifiers.items()):

    # fit te data and tag outliers
    if clf_name == "Local Outlier Factor":
        y_pred = clf.fit_predict(X)
        print("LOF executed")
        scores_pred = clf.negative_outlier_factor_
        # Export the classifier to a file
        with open('model.pkl', 'wb') as model_file:
            pickle.dump(clf, model_file)
    else:
        clf.fit(X)
        scores_pred = clf.decision_function(X)
        y_pred = clf.predict(X)
        print("IF executed")
        # Export the classifier to a file
        with open('model.pkl', 'wb') as model_file:
            pickle.dump(clf, model_file)
    # Reshape the prediction values to 0 for valid and 1 for fraudulent
    y_pred[y_pred == 1] = 0
    y_pred[y_pred == -1] = 1

    n_errors = (y_pred != Y).sum()

# run classification metrics 
print('{}:{}'.format(clf_name, n_errors))
print(accuracy_score(Y, y_pred ))
print(classification_report(Y, y_pred ))

and here's the output in the Jupyter Notebook:

Isolation Forest:7

0.93

               precision    recall  f1-score   support


         0       0.97      0.96      0.96        94
         1       0.43      0.50      0.46         6

  avg / total    0.94      0.93      0.93       100

I have deployed this model to Google Cloud ML-Engine and then try to serve it using the following python script:

import os
from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name('Machine Learning 001-dafe42dfb46f.json')

PROJECT_ID = "machine-learning-001-201312"
VERSION_NAME = "v1"
MODEL_NAME = "mlfd"
service = discovery.build('ml', 'v1', credentials=credentials)
name = 'projects/{}/models/{}'.format(PROJECT_ID, MODEL_NAME)
name += '/versions/{}'.format(VERSION_NAME)

data = [[265580, 7, 68728, 8.36, 4.76, 84.12, 79.36, 3346, 1, 11.99, 1.14,655012, 0.65, 258374, 0, 84.12] ]

response = service.projects().predict(
    name=name,
    body={'instances': data}
).execute()

if 'error' in response:
  print (response['error'])
else:
  online_results = response['predictions']
  print(online_results)

Here is the output of this script:

Prediction failed: Exception during sklearn prediction: 'LocalOutlierFactor' object has no attribute 'predict'

4条回答
你好瞎i
2楼-- · 2019-06-08 00:57

LocalOutlierFactor does not have a predict method, but only a private _predict method. Here is the justification from the source.

def _predict(self, X=None):
    """Predict the labels (1 inlier, -1 outlier) of X according to LOF.
    If X is None, returns the same as fit_predict(X_train).
    This method allows to generalize prediction to new observations (not
    in the training set). As LOF originally does not deal with new data,
    this method is kept private.

https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/neighbors/lof.py#L200

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-08 00:59

I worked on a project which seems to be very identic. I got the same error. My problem was a typo in the if-statement.

Regards Lorenz

查看更多
Animai°情兽
4楼-- · 2019-06-08 01:04

Surprisingly, the issue is the runtime version, it will be solved when you will re-create your model version as:

gcloud beta ml-engine versions create $VERSION_NAME  --model $MODEL_NAME --origin $DEPLOYMENT_SOURCE --runtime-version="1.6" --framework $FRAMEWORK --python-version="3.5"

Use Runtime version 1.6 instead of 1.5, turn it to a running model at least.

查看更多
地球回转人心会变
5楼-- · 2019-06-08 01:05

It looks like this may be a Python version thing (although it's not clear to me why scikit learn behaves differently in Python 2 vs. Python 3). I was able to verify locally -- on the same machine -- that my Python 2 install reproduces the error above while Python 3 succeeds (both are using sci-kit learn 0.19.1).

The solution is to specify the python version when you deploy the model (note the last line which, if omitted, defaults to "2.7"):

gcloud beta ml-engine versions create $VERSION_NAME \
    --model $MODEL_NAME --origin $DEPLOYMENT_SOURCE \
    --runtime-version="1.5" --framework $FRAMEWORK
    --python-version="3.5"
查看更多
登录 后发表回答