Coverage for mlstatpy/ml/kppv.py: 92%

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

37 statements

1# -*- coding: utf-8 -*-

2"""

3@file

4@brief Implements classic k-nn.

5"""

6import numpy

7import numpy.linalg

8from scipy.spatial.distance import euclidean

11class NuagePoints:

12 """

13 Définit une classe de nuage de points.

14 On suppose qu'ils sont définis par une matrice,

15 chaque ligne est un élément.

16 """

18 def __init__(self):

19 """

20 constructeur

21 """

22 pass

24 def fit(self, X, y=None):

25 """

26 Follows sklearn API.

28 @param X training set

29 @param y labels

30 """

31 self.nuage = X

32 self.labels = y

34 def kneighbors(self, X, n_neighbors=1, return_distance=True):

35 """

36 Return the k nearest neighbors.

38 @param X test set

39 @param n_neighbors number of neighbors

40 @param return_distance return distance as well

41 @return array (dist), array (indices)

42 """

43 if n_neighbors != 1:

44 raise NotImplementedError( # pragma: no cover

45 "Not implemented when n_neighbors != 1.")

46 if not return_distance:

47 raise NotImplementedError( # pragma: no cover

48 "Not implemented when return_distance is False.")

50 dist = numpy.zeros(X.shape[0])

51 ind = numpy.zeros(X.shape[0], dtype=numpy.int64)

53 for i in range(X.shape[0]):

54 row = X[i, :]

55 row.resize((1, X.shape[1]))

56 r = self.ppv(row)

57 dist[i], ind[i] = r

58 return dist, ind

60 @property

61 def shape(self):

62 """

63 Retourne la dimension du nuage.

64 """

65 return self.nuage.shape

67 def distance(self, obj1, obj2):

68 """

69 Retourne une distance entre deux éléments.

71 @param obj1 object 1

72 @param obj2 object 2

73 @return distance

74 """

75 return euclidean(obj1, obj2)

77 def label(self, i):

78 """

79 Retourne le label de l'object d'indice ``i``.

81 @param i indice

82 @return label or None if there is no label

83 """

84 return self.label[i] if self.label is not None else None

86 def ppv(self, obj):

87 """

88 Retourne l'élément le plus proche de obj et sa distance avec obj.

90 @param obj object

91 @return ``tuple(dist, index)``

92 """

93 ones = numpy.ones((self.nuage.shape[0], 1))

94 mat = ones @ obj

95 if len(mat.shape) == 1:

96 mat.resize((mat.shape[0], 1))

97 delta = self.nuage - mat

98 norm = numpy.linalg.norm(delta, axis=1)

99 i = numpy.argmin(norm)

100 return norm[i], i