コード例 #1
0
  def test_finite_differences(self):
    """Test gradient of loss function

    Assert that the gradient is almost equal to its finite differences
    approximation.
    """
    # Initialize the transformation `M`, as well as `X`, and `y` and `MLKR`
    X, y = make_regression(n_features=4, random_state=1, n_samples=20)
    X, y = check_X_y(X, y)
    M = np.random.randn(2, X.shape[1])
    mlkr = MLKR()
    mlkr.n_iter_ = 0

    def fun(M):
      return mlkr._loss(M, X, y)[0]

    def grad_fn(M):
      return mlkr._loss(M, X, y)[1].ravel()

    # compute relative error
    rel_diff = check_grad(fun, grad_fn, M.ravel()) / np.linalg.norm(grad_fn(M))
    np.testing.assert_almost_equal(rel_diff, 0.)
コード例 #2
0
  def test_mlkr(self):
    mlkr = MLKR(num_dims=2)
    mlkr.fit(self.X, self.y)
    res_1 = mlkr.transform(self.X)

    mlkr = MLKR(num_dims=2)
    res_2 = mlkr.fit_transform(self.X, self.y)

    assert_array_almost_equal(res_1, res_2)
コード例 #3
0
 def test_iris(self):
   mlkr = MLKR()
   mlkr.fit(self.iris_points, self.iris_labels)
   csep = class_separation(mlkr.transform(self.iris_points), self.iris_labels)
   self.assertLess(csep, 0.25)
コード例 #4
0
ファイル: test_utils.py プロジェクト: lejeunel/metric-learn
        [learner for (learner, _) in pairs_learners]))

classifiers = [(Covariance(), build_classification),
               (LFDA(), build_classification), (LMNN(), build_classification),
               (NCA(), build_classification), (RCA(), build_classification),
               (ITML_Supervised(max_iter=5), build_classification),
               (LSML_Supervised(), build_classification),
               (MMC_Supervised(max_iter=5), build_classification),
               (RCA_Supervised(num_chunks=5), build_classification),
               (SDML_Supervised(prior='identity',
                                balance_param=1e-5), build_classification)]
ids_classifiers = list(
    map(lambda x: x.__class__.__name__,
        [learner for (learner, _) in classifiers]))

regressors = [(MLKR(init='pca'), build_regression)]
ids_regressors = list(
    map(lambda x: x.__class__.__name__,
        [learner for (learner, _) in regressors]))

WeaklySupervisedClasses = (_PairsClassifierMixin, _QuadrupletsClassifierMixin)

tuples_learners = pairs_learners + quadruplets_learners
ids_tuples_learners = ids_pairs_learners + ids_quadruplets_learners

supervised_learners = classifiers + regressors
ids_supervised_learners = ids_classifiers + ids_regressors

metric_learners = tuples_learners + supervised_learners
ids_metric_learners = ids_tuples_learners + ids_supervised_learners
コード例 #5
0
 def test_mlkr(self):
   mlkr = MLKR(num_dims=2)
   mlkr.fit(self.X, self.y)
   L = mlkr.transformer_
   assert_array_almost_equal(L.T.dot(L), mlkr.get_mahalanobis_matrix())
コード例 #6
0
ファイル: test_utils.py プロジェクト: tomery/metric-learn
        [learner for (learner, _) in pairs_learners]))

classifiers = [(Covariance(), build_classification),
               (LFDA(), build_classification), (LMNN(), build_classification),
               (NCA(), build_classification), (RCA(), build_classification),
               (ITML_Supervised(max_iter=5), build_classification),
               (LSML_Supervised(), build_classification),
               (MMC_Supervised(max_iter=5), build_classification),
               (RCA_Supervised(num_chunks=10), build_classification),
               (SDML_Supervised(use_cov=False,
                                balance_param=1e-5), build_classification)]
ids_classifiers = list(
    map(lambda x: x.__class__.__name__,
        [learner for (learner, _) in classifiers]))

regressors = [(MLKR(), build_regression)]
ids_regressors = list(
    map(lambda x: x.__class__.__name__,
        [learner for (learner, _) in regressors]))

WeaklySupervisedClasses = (_PairsClassifierMixin, _QuadrupletsClassifierMixin)

tuples_learners = pairs_learners + quadruplets_learners
ids_tuples_learners = ids_pairs_learners + ids_quadruplets_learners

supervised_learners = classifiers + regressors
ids_supervised_learners = ids_classifiers + ids_regressors

metric_learners = tuples_learners + supervised_learners
ids_metric_learners = ids_tuples_learners + ids_supervised_learners
コード例 #7
0
 def test_mlkr(self):
   mlkr = MLKR(n_components=2)
   mlkr.fit(self.X, self.y)
   L = mlkr.components_
   assert_array_almost_equal(L.T.dot(L), mlkr.get_mahalanobis_matrix())
コード例 #8
0
 def test_iris(self):
   mlkr = MLKR()
   mlkr.fit(self.iris_points, self.iris_labels)
   csep = class_separation(mlkr.transform(), self.iris_labels)
   self.assertLess(csep, 0.25)
コード例 #9
0
 def test_mlkr(self):
     check_estimator(MLKR())
コード例 #10
0
class MetricLearner:
    def __init__(self):
        self._learner = None
        self._trained = ObservableObject(False)

    def train_metric_learner_supervised(self, landmark_fin_ok,
                                        landmark_fin_bad, path):

        landmarks = np.concatenate((landmark_fin_ok, landmark_fin_bad))
        landmarks = landmarks.reshape(landmarks.shape[0],
                                      landmarks.shape[1] * landmarks.shape[2])
        labels = []

        for i in range(len(landmark_fin_ok)):
            labels.append(1)
        for i in range(len(landmark_fin_bad)):
            labels.append(-1)

        self._learner = MLKR(preprocessor=landmarks)
        self._learner.fit(landmarks, labels)
        self.save_learner(path)

    def train_metric_learner_supervised_all_landmarks(self, landmark_init_ok,
                                                      landmark_fin_ok,
                                                      landmark_fin_bad, path):
        landmarks = np.concatenate(
            (landmark_init_ok, landmark_fin_ok, landmark_fin_bad))
        landmarks = landmarks.reshape(landmarks.shape[0],
                                      landmarks.shape[1] * landmarks.shape[2])
        labels = []

        for i in range(len(landmark_init_ok)):
            labels.append(0)
        for i in range(len(landmark_fin_ok)):
            labels.append(1)
        for i in range(len(landmark_fin_bad)):
            labels.append(-1)

        # Utilizzo anche i video corretti degli altri esercizi
        for categoria in os.listdir("Exercises"):
            cat_path = Path("Exercises/" + categoria)
            if cat_path.is_dir():
                for name in os.listdir(cat_path):
                    ex_path = Path("Exercises/" + categoria + "/" + name)
                    if ex_path.is_dir() and ex_path != Path(path):
                        pathCorrect = Path("Exercises/" + categoria + "/" +
                                           name + "/Correct")
                        for file in os.listdir(pathCorrect):
                            if file.endswith(".npy"):
                                pathFile = str(pathCorrect) + "\\" + file
                                landmark = np.load(
                                    pathFile,
                                    allow_pickle=True)[38].reshape(1, 68 * 2)
                                landmarks = np.concatenate(
                                    (landmarks, landmark))
                                labels.append(-1)

        self._learner = MLKR(preprocessor=landmarks)
        self._learner.fit(landmarks, labels)
        self.save_learner(path)

    def get_learner(self):
        return self._learner

    def save_learner(self, path):
        joblib.dump(self._learner, path + "TreanedModel.sav")

    def load_learner(self, path):
        self._learner = joblib.load(path + "TreanedModel.sav")

    def remove_learner(self, path):
        os.remove(path + ".sav")
コード例 #11
0
 def test_mlkr(self):
   mlkr = MLKR(num_dims=2)
   mlkr.fit(self.X, self.y)
   L = mlkr.transformer_
   assert_array_almost_equal(L.T.dot(L), mlkr.metric())
コード例 #12
0
 def mlkr(data, label, dim):
     mlkr = MLKR(num_dims=dim)
     mlkr.fit(data, label)
     result = mlkr.transform(data)
     return result
コード例 #13
0
 def test_mlkr(self):
   mlkr = MLKR(num_dims=2)
   mlkr.fit(self.X, self.y)
   L = mlkr.transformer_
   assert_array_almost_equal(L.T.dot(L), mlkr.get_mahalanobis_matrix())
コード例 #14
0
 def test_mlkr(self):
   mlkr = MLKR(num_dims=2)
   mlkr.fit(self.X, self.y)
   L = mlkr.transformer()
   assert_array_almost_equal(L.T.dot(L), mlkr.metric())