Настройка параметров переменного наименьшего квадрата - PullRequest
0 голосов
/ 19 апреля 2020

Контекст: я работаю над созданием системы рекомендаций, использующей неявную обратную связь (заказы) с использованием неявной библиотеки в python.

Проблема: при попытке настроить параметры, чтобы узнать наилучшие параметры для используйте, выход не зацикливается на всех переменных и не вычисляет au c. Как я могу убедиться, что он зацикливается на всех комбинациях, и добавить в словарь, если комбинации приводят к наибольшему значению AU C? Также, пожалуйста, не стесняйтесь сообщить мне, если есть библиотека, которую я могу использовать для настройки, так как я не знал, как использовать gridsearchCV, например, для этого варианта использования (модель ALS).

В коде : training_set2 - измененная версия исходного training_set с определенным процентом пар элементов пользователя, для которых первоначально взаимодействие было установлено на ноль.

validation_set - копия исходной матрицы training_set, без изменений, поэтому она может использоваться, чтобы увидеть, как порядок ранжирования сравнивается с фактическими взаимодействиями.

Ожидаемый результат: словарь со всеми комбинациями в порядке des c, где последняя является комбинацией с самым высоким значением AU C оценка. Эта комбинация будет той, которую я буду использовать для своего тестового набора.


    def auc_score(predictions, test):
        fpr, tpr, thresholds = metrics.roc_curve(test, predictions)
        return metrics.auc(fpr, tpr)

    def calc_mean_auc(training_set, altered_users, predictions, test_set):
        '''
        This function will calculate the mean AUC by user for any user that had their user-item matrix altered. 
        '''
        store_auc = [] # An empty list to store the AUC for each user that had an item removed from the training set
        item_vecs = predictions[1]
        for user in altered_users: # Iterate through each user that had an item altered
            training_row = training_set[user,:].toarray().reshape(-1) # Get the training set row
            zero_inds = np.where(training_row == 0) # Find where the interaction had not yet occurred
            # Get the predicted values based on our user/item vectors
            user_vec = predictions[0][user,:]
            pred = user_vec.dot(item_vecs).toarray()[0,zero_inds].reshape(-1)
            # Get only the items that were originally zero
            # Select all ratings from the MF prediction for this user that originally had no iteraction
            actual = test_set[user,:].toarray()[0,zero_inds].reshape(-1) 
            # Select the binarized yes/no interaction pairs from the original full data
            # that align with the same pairs in training 
            store_auc.append(auc_score(pred, actual)) # Calculate AUC for the given user and store
        # End users iteration

        return float('%.3f'%np.mean(store_auc)) 
    ...
    latent_factors = [5, 10, 20, 40, 80]
    regularizations = [0.01, 0.1, 1., 10., 100.]
    regularizations.sort()
    iter_array = [1, 2, 5, 10, 25, 50, 100]

    best_params = {}
    best_params['n_factors'] = latent_factors[0]
    best_params['reg'] = regularizations[0]
    best_params['n_iter'] = 0
    best_params['auc_result'] = np.inf
    best_params['model'] = None

    for fact in latent_factors:
        print('Factors: {}'.format(fact))
        for reg in regularizations:
            print ('Regularization: {}'.format(reg))
            for ite in iter_array:
                print ('Iteration: {}'.format(ite))
                model = implicit.als.AlternatingLeastSquares(
                    factors=fact,
                    regularization=reg, 
                    iterations=ite)



    model.fit((training2_set.T * 15).astype('double'))
                customers_vecs = model.user_factors
                restaurant_vecs = model.item_factors
                auc_result = calc_mean_auc(training2_set, cust_altered2, 
                  [sparse.csr_matrix(customers_vecs), sparse.csr_matrix(restaurant_vecs.T)], validation_set)
                if auc_result > best_params['auc_result']:
                    best_params['n_factors'] = fact
                    best_params['reg'] = reg
                    best_params['n_iter'] = ite
                    best_params['auc_result'] = auc_result
                    best_params['model'] = 'AlternatingLeastSquare'
                    print ('New optimal hyperparameters')
                    print (pd.Series(best_params))

Я не могу опубликовать изображение, но я получаю вывод:

</b>
Factors: 5</b>
Regularization: 0.01</b>
Iteration: 1</b>

n_factors     5.00</b>
reg           0.01</b>
n_iter        0.00</b>
auc_result     inf</b>
model          NaN</b>
dtype: float64</b>
Iteration: 2</b>

n_factors     5.00</b>
reg           0.01</b>
n_iter        0.00</b>
auc_result     inf</b>
model          NaN</b>
dtype: float64</b>
Iteration: 5</b>

1 Ответ

0 голосов
/ 19 апреля 2020

Вы сохраняете только параметры best - if auc_error < best_params['auc_error']:

Используйте collection.defaultdict для накопления всех параметров в списках

...
from collections import defaultdict
best_params = defaultdict(list)
##best_params = {}
##best_params['n_factors'] = latent_factors[0]
##best_params['reg'] = regularizations[0]
##best_params['n_iter'] = 0
##best_params['auc_error'] = np.inf
##best_params['model'] = None
...
for fact in latent_factors:
    ...
        ...
            ##if auc_error < best_params['auc_error']:
            best_params['n_factors'].append(fact)
            best_params['reg'].append(reg)
            best_params['n_iter'].append(ite)
            best_params['auc_error'].append(auc_error)
            best_params['model'].append('AlternatingLeastSquare')
            ##print ('New optimal hyperparameters')

Похоже, вы используете Pandas, поэтому создайте DataFrame и сортируйте его.

df = pd.DataFrame(best_params)
df = df.sort_values('auc_error')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...