Exemplo n.º 1
0
    def test_compare_numpy(self):
        """Compara con numpy"""
        A = np.array([
            [1, 0, 1],
            [1, 1, 1],
            [0, 1, 1],
        ])
        # Ecuaciones normales es malo con un numero de condicion alto
        # print(np.linalg.cond(A))

        b = np.array([1, 2, 3]).reshape(3, 1)

        # fit
        clf = metnum.LinearRegression()
        clf.fit(A, b)

        # predict
        A_monio = np.array([
            [0, 1, 1],
            [1, 1, 4],
            [0, 0, 0],
        ])

        y_pred = clf.predict(A_monio)

        # con np.linalg
        x = np.linalg.solve((A.T @ A), A.T @ b)
        y = A_monio @ x

        self.assert_allclose(y_pred, y)
Exemplo n.º 2
0
def predict(x, y):
    '''
    Uses our regressor and test against the same set
    TODO: get a better name
    '''
    linear_regressor = metnum.LinearRegression()
    linear_regressor.fit(x, y)
    prediction = linear_regressor.predict(x)  # returns a matrix in nx1
    return prediction[:, 0]  # to vector
Exemplo n.º 3
0
    def fit(self, df: pd.DataFrame):
        segments = self._segment(df)

        for segment in segments:
            clf = metnum.LinearRegression()
            A = self._get_A(segment)
            b = self._get_b(segment)
            
            clf.fit(A, b)

            self._clfs.append(clf)
Exemplo n.º 4
0
    def _regresionar_segmento(self, df_segment, segment_name):
        # Separa la matriz A y el vector de los resultados reales (los precios por ej.) para pasarselos al segmento y que los fitee
        A = df_segment[self.features].values
        reales = df_segment[self.predict_column].values

        # Si NO hay por lo menos k elementos para hacer kfold, este segmento no va a aportar información relevante para el modelo
        if len(reales) < self.kfold:
            err = RuntimeError(
                f'{segment_name} tiene menos de {self.kfold} elementos')
            print(
                f'Error calculando metricas en segmento {str(segment_name)}:\n{err}'
            )
            return

        # Creo el segmento
        segment = Segment(str(segment_name), metnum.LinearRegression(),
                          self.features, self.metrics(), self.kfold)
        #print(f'Segemento: {segment_name} elementos \n')
        # Fit y predict
        segment.fit(A, reales)
        # Guardo el segmento
        self.segments[segment_name] = segment
Exemplo n.º 5
0
    def test_trivial(self):
        """
        Testea que se comporta de forma correcta para una tabla de
        datos trivial.
        """

        # Lo entrenamos con algo trivial, la identidad y un canonico
        A = np.eye(3)
        b = np.array([[1], [0], [0]])

        clf = metnum.LinearRegression()
        # AtA = I
        # AtA x = At b sii x = b
        clf.fit(A, b)

        # Hacemos predict de la identidad para obtener el vector debajo
        y_pred = clf.predict(np.eye(3))
        self.assert_allclose(y_pred, b)

        # Ahora predict de otra matriz un poco mas complicada
        y_pred = clf.predict(np.diag([3, 3, 3]))
        self.assert_allclose(y_pred, np.array([3, 0, 0]).reshape(3, 1))