Beispiel #1
0
class NMFImpl():

    def __init__(self, n_components=None, init=None, solver='cd', beta_loss='frobenius', tol=0.0001, max_iter=200, random_state=None, alpha=0.0, l1_ratio=0.0, verbose=0, shuffle=False):
        self._hyperparams = {
            'n_components': n_components,
            'init': init,
            'solver': solver,
            'beta_loss': beta_loss,
            'tol': tol,
            'max_iter': max_iter,
            'random_state': random_state,
            'alpha': alpha,
            'l1_ratio': l1_ratio,
            'verbose': verbose,
            'shuffle': shuffle}

    def fit(self, X, y=None):
        self._sklearn_model = SKLModel(**self._hyperparams)
        if (y is not None):
            self._sklearn_model.fit(X, y)
        else:
            self._sklearn_model.fit(X)
        return self

    def transform(self, X):
        return self._sklearn_model.transform(X)
class NMFRecommender(BaseEstimator, RegressorMixin):
    def __init__(self, n_components):
        self.nmf = NMF(n_components=2, init='random', random_state=0)
        self.user_ids_dict = {}
        self.book_isbns_dict = {}

    def fit(self, X, y=None):
        self.sparse_matrix = X['sparse_matrix']
        self.user_ids_dict = X['user_ids_dict']
        self.book_isbns_dict = X['book_isbns_dict']
        self.nmf.fit(X['sparse_matrix'])

    def predict(self, X, y=None):
        ratings = X['ratings']
        user_representations = self.nmf.transform(self.sparse_matrix)
        book_representations = self.nmf.components_
        estimations = []
        for i in tqdm(range(len(ratings))):
            estimation = np.dot(
                user_representations[self.user_ids_dict[
                    ratings.iloc[i]['User-ID']]], book_representations)[
                        self.book_isbns_dict[ratings.iloc[i]['ISBN']]]
            estimations.append(estimation)
        return estimations

    def fit_predict(self, X, y=None):
        self.fit(X, y)
        return self.predict(X, y)