Esempio n. 1
0
    def test_search_neighbors_precomputed(self):
        d = pairwise_distance(lp_distance)
        distances = d(self.X[:4], self.X[:4])

        nn = NearestNeighbors(metric='precomputed', n_neighbors=2)
        nn.fit(distances, self.y[:4])

        _, neighbors = nn.kneighbors(distances)

        result = np.array([[0, 3], [1, 2], [2, 1], [3, 0]])
        np.testing.assert_array_almost_equal(neighbors, result)
Esempio n. 2
0
    def test_knn_functional_response_precomputed(self):
        knnr = KNeighborsRegressor(n_neighbors=4, weights='distance',
                                   metric='precomputed')
        d = pairwise_distance(lp_distance)
        distances = d(self.X[:4], self.X[:4])

        knnr.fit(distances, self.X[:4])

        res = knnr.predict(distances)
        np.testing.assert_array_almost_equal(res.data_matrix,
                                             self.X[:4].data_matrix)
Esempio n. 3
0
    def test_lof_fit_predict(self):
        """ Test same results with different forms to call fit_predict"""

        # Outliers
        expected = np.ones(len(self.fd_lof))
        expected[0:2] = -1

        # With default l2 distance
        lof = LocalOutlierFactor()
        res = lof.fit_predict(self.fd_lof)
        np.testing.assert_array_equal(expected, res)

        # With explicit l2 distance
        lof2 = LocalOutlierFactor(metric=lp_distance)
        res2 = lof2.fit_predict(self.fd_lof)
        np.testing.assert_array_equal(expected, res2)

        d = pairwise_distance(lp_distance)
        distances = d(self.fd_lof, self.fd_lof)

        # With precompute distances
        lof3 = LocalOutlierFactor(metric="precomputed")
        res3 = lof3.fit_predict(distances)
        np.testing.assert_array_equal(expected, res3)

        # With multivariate sklearn
        lof4 = LocalOutlierFactor(metric="euclidean", multivariate_metric=True)
        res4 = lof4.fit_predict(self.fd_lof)
        np.testing.assert_array_equal(expected, res4)

        # Other way of call fit_predict, undocumented in sklearn
        lof5 = LocalOutlierFactor(novelty=True)
        res5 = lof5.fit(self.fd_lof).predict()
        np.testing.assert_array_equal(expected, res5)

        # Check values of negative outlier factor
        negative_lof = [-7.1068, -1.5412, -0.9961, -0.9854, -0.9896, -1.0993,
                        -1.065, -0.9871, -0.9821, -0.9955, -1.0385, -1.0072,
                        -0.9832, -1.0134, -0.9939, -1.0074, -0.992, -0.992,
                        -0.9883, -1.0012, -1.1149, -1.002, -0.9994, -0.9869,
                        -0.9726, -0.9989, -0.9904]

        np.testing.assert_array_almost_equal(
            lof.negative_outlier_factor_.round(4), negative_lof)

        # Check same negative outlier factor
        np.testing.assert_array_almost_equal(lof.negative_outlier_factor_,
                                             lof2.negative_outlier_factor_)

        np.testing.assert_array_almost_equal(lof.negative_outlier_factor_,
                                             lof3.negative_outlier_factor_)
Esempio n. 4
0
    def test_functional_regression_distance_weights(self):

        knnr = KNeighborsRegressor(
            weights='distance', n_neighbors=10)
        knnr.fit(self.X[:10], self.X[:10])
        res = knnr.predict(self.X[11])

        d = pairwise_distance(lp_distance)
        distances = d(self.X[:10], self.X[11]).flatten()

        weights = 1 / distances
        weights /= weights.sum()

        response = self.X[:10].mean(weights=weights)
        np.testing.assert_array_almost_equal(res.data_matrix,
                                             response.data_matrix)
Esempio n. 5
0
import unittest

import numpy as np

from skfda import FDataGrid
from skfda.datasets import make_multimodal_samples
from skfda.misc.metrics import (fisher_rao_distance, amplitude_distance,
                                phase_distance, pairwise_distance, lp_distance,
                                warping_distance)
from skfda.preprocessing.registration import (elastic_registration, to_srsf,
                                              from_srsf,
                                              elastic_registration_warping,
                                              invert_warping,
                                              normalize_warping)

metric = pairwise_distance(lp_distance)
pairwise_fisher_rao = pairwise_distance(fisher_rao_distance)


class TestElasticRegistration(unittest.TestCase):
    """Test elastic registration"""
    def setUp(self):
        """Initialization of samples"""
        template = make_multimodal_samples(n_samples=1, std=0, random_state=1)
        self.template = template
        self.template_rep = template.concatenate(template).concatenate(
            template)
        self.unimodal_samples = make_multimodal_samples(n_samples=3,
                                                        random_state=1)

        t = np.linspace(-3, 3, 9)
lower = sample - radius
upper = sample + radius
fig.axes[0].fill_between(sample.grid_points[0],
                         lower.data_matrix.flatten(),
                         upper.data_matrix[0].flatten(),
                         alpha=.25,
                         color='C1')

##############################################################################
#
# In this case, all the neighbors in the ball belong to the first class, so
# this will be the class predicted.
#

# Creation of pairwise distance
l_inf = pairwise_distance(lp_distance, p=np.inf)
distances = l_inf(sample, X_train)[0]  # L_inf distances to 'sample'

# Plot samples in the ball
fig = X_train[distances <= radius].plot(color='C0')
sample.plot(fig=fig, color='red', linewidth=3)
fig.axes[0].fill_between(sample.grid_points[0],
                         lower.data_matrix.flatten(),
                         upper.data_matrix[0].flatten(),
                         alpha=.25,
                         color='C1')

##############################################################################
#
# We will fit the classifier
# :class:`~skfda.ml.classification.RadiusNeighborsClassifier`, which has a
Esempio n. 7
0
plt.figure("means")

fd.mean().plot(label=r"cross-sectional mean")

mean_el = elastic_mean(fd)
mean_el.plot(label=f"elastic mean")
#plt.ylim(ylims)
plt.legend()

plt.tight_layout()
plt.figure("dataset-by-amplitude")

# Get colors
cmap = plt.cm.Reds_r

amp = pairwise_distance(amplitude_distance)

distances = amp(mean_el, fd)[0]
#print(distances)

index = np.argsort(distances)[::-1]
maximun = np.max(distances)
minimun = np.min(distances)

color = cmap((distances - minimun) / (maximun - minimun))
#print(color)

for i in range(len(fd)):
    indice = int(index[i])
    fd[indice].plot(color=color[indice])