|
| 1 | +# Copyright 2020 The SQLFlow Authors. All rights reserved. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +import os |
| 15 | +import pickle |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +import tensorflow as tf |
| 19 | +from sklearn.svm import OneClassSVM as SklearnOneClassSVM |
| 20 | + |
| 21 | +MODEL_PATH = "one_class_svm_model" |
| 22 | + |
| 23 | + |
| 24 | +class OneClassSVM(tf.keras.Model): |
| 25 | + def __init__(self, |
| 26 | + feature_columns=None, |
| 27 | + kernel='rbf', |
| 28 | + degree=3, |
| 29 | + gamma='scale', |
| 30 | + coef0=0.0, |
| 31 | + tol=0.001, |
| 32 | + nu=0.5, |
| 33 | + shrinking=True, |
| 34 | + cache_size=200, |
| 35 | + verbose=False, |
| 36 | + max_iter=-1): |
| 37 | + if os.path.exists(MODEL_PATH): |
| 38 | + with open(MODEL_PATH, "rb") as f: |
| 39 | + self.svm = pickle.load(f) |
| 40 | + else: |
| 41 | + self.svm = SklearnOneClassSVM(kernel=kernel, |
| 42 | + degree=degree, |
| 43 | + gamma=gamma, |
| 44 | + coef0=coef0, |
| 45 | + tol=tol, |
| 46 | + nu=nu, |
| 47 | + shrinking=shrinking, |
| 48 | + cache_size=cache_size, |
| 49 | + verbose=verbose, |
| 50 | + max_iter=max_iter) |
| 51 | + |
| 52 | + def concat_features(self, features): |
| 53 | + assert isinstance(features, dict) |
| 54 | + each_feature = [] |
| 55 | + for _, v in features.items(): |
| 56 | + each_feature.append(v.numpy()) |
| 57 | + return np.concatenate(each_feature, axis=1) |
| 58 | + |
| 59 | + def sqlflow_train_loop(self, dataset): |
| 60 | + X = [] |
| 61 | + for features in dataset: |
| 62 | + X.append(self.concat_features(features)) |
| 63 | + X = np.concatenate(X) |
| 64 | + |
| 65 | + self.svm.fit(X) |
| 66 | + with open(MODEL_PATH, "wb") as f: |
| 67 | + pickle.dump(self.svm, f, protocol=2) |
| 68 | + |
| 69 | + def sqlflow_predict_one(self, features): |
| 70 | + features = self.concat_features(features) |
| 71 | + pred = self.svm.predict(features) |
| 72 | + return [pred] |
0 commit comments