cornac icon indicating copy to clipboard operation
cornac copied to clipboard

[BUG] BiVAECF - AttributeError: 'csc_matrix' object has no attribute 'A'

Open dvquy13 opened this issue 1 year ago • 0 comments

Description

BiVAECF fails to run on quick start examples

Code

Below is the basic test case added w.r.t. to the error:

import unittest

from cornac.data import Dataset, Reader
from cornac.models import BiVAECF


class TestRecommender(unittest.TestCase):
    def setUp(self):
        self.data = Reader().read("./tests/data.txt")

    def test_run(self):
        bivae = BiVAECF(k=1, seed=123)
        dataset = Dataset.from_uir(self.data)
        # Assert runs without error
        bivae.fit(dataset)

[!CAUTION] Error:

>               i_batch = i_batch.A
E               AttributeError: 'csc_matrix' object has no attribute 'A'
Detailed error logs
============================= test session starts ==============================
platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /home/dvquys/miniconda3/envs/cornac/bin/python3
cachedir: .pytest_cache
rootdir: /home/dvquys/frostmourne/oss/cornac
configfile: pytest.ini
plugins: xdist-3.6.1, cov-5.0.0, pep8-1.0.6, typeguard-4.3.0
collecting ... collected 1 item

tests/cornac/models/bivae/test_recommender.py::TestRecommender::test_run FAILED [100%]

=================================== FAILURES ===================================
___________________________ TestRecommender.test_run ___________________________

self = <test_recommender.TestRecommender testMethod=test_run>

    def test_run(self):
        bivae = BiVAECF(k=1, seed=123)
        dataset = Dataset.from_uir(self.data)
        # Assert runs without error
>       bivae.fit(dataset)

tests/cornac/models/bivae/test_recommender.py:15: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
cornac/models/bivaecf/recom_bivaecf.py:178: in fit
    learn(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

bivae = BiVAE(
  (act_fn): Tanh()
  (user_encoder): Sequential(
    (fc0): Linear(in_features=10, out_features=20, bias=True)
...u): Linear(in_features=20, out_features=1, bias=True)
  (item_std): Linear(in_features=20, out_features=1, bias=True)
)
train_set = <cornac.data.dataset.Dataset object at 0x7e31a29a4dd0>
n_epochs = 100, batch_size = 100, learn_rate = 0.001, beta_kl = 1.0
verbose = False, device = device(type='cuda', index=0), dtype = torch.float32

    def learn(
        bivae,
        train_set,
        n_epochs,
        batch_size,
        learn_rate,
        beta_kl,
        verbose,
        device=torch.device("cpu"),
        dtype=torch.float32,
    ):
        user_params = it.chain(
            bivae.user_encoder.parameters(),
            bivae.user_mu.parameters(),
            bivae.user_std.parameters(),
        )
    
        item_params = it.chain(
            bivae.item_encoder.parameters(),
            bivae.item_mu.parameters(),
            bivae.item_std.parameters(),
        )
    
        if bivae.cap_priors.get("user", False):
            user_params = it.chain(user_params, bivae.user_prior_encoder.parameters())
            user_features = train_set.user_feature.features[: train_set.num_users]
    
        if bivae.cap_priors.get("item", False):
            item_params = it.chain(item_params, bivae.item_prior_encoder.parameters())
            item_features = train_set.item_feature.features[: train_set.num_items]
    
        u_optimizer = torch.optim.Adam(params=user_params, lr=learn_rate)
        i_optimizer = torch.optim.Adam(params=item_params, lr=learn_rate)
    
        x = train_set.matrix.copy()
        x.data = np.ones_like(x.data)  # Binarize data
        tx = x.transpose()
    
        progress_bar = trange(1, n_epochs + 1, disable=not verbose)
        for _ in progress_bar:
            # item side
            i_sum_loss = 0.0
            i_count = 0
            for i_ids in train_set.item_iter(batch_size, shuffle=False):
                i_batch = tx[i_ids, :]
>               i_batch = i_batch.A
E               AttributeError: 'csc_matrix' object has no attribute 'A'

cornac/models/bivaecf/bivae.py:201: AttributeError
============================= slowest 20 durations =============================
1.57s call     tests/cornac/models/bivae/test_recommender.py::TestRecommender::test_run

(2 durations < 0.005s hidden.  Use -vv to show these durations.)
=========================== short test summary info ============================
FAILED tests/cornac/models/bivae/test_recommender.py::TestRecommender::test_run
============================== 1 failed in 2.09s ===============================

In which platform does it happen?

Ubuntu 24.04, cornac==2.2.1

How do we replicate the issue?

Run the cornac quick start examples with BiVAECF added to the list of models:

import cornac
from cornac.eval_methods import RatioSplit
from cornac.models import MF, PMF, BPR, BiVAECF
from cornac.metrics import MAE, RMSE, Precision, Recall, NDCG, AUC, MAP

# load the built-in MovieLens 100K and split the data based on ratio
ml_100k = cornac.datasets.movielens.load_feedback()
rs = RatioSplit(data=ml_100k, test_size=0.2, rating_threshold=4.0, seed=123)

# initialize models, here we are comparing: Biased MF, PMF, and BPR
mf = MF(k=10, max_iter=25, learning_rate=0.01, lambda_reg=0.02, use_bias=True, seed=123)
pmf = PMF(k=10, max_iter=100, learning_rate=0.001, lambda_reg=0.001, seed=123)
bpr = BPR(k=10, max_iter=200, learning_rate=0.001, lambda_reg=0.01, seed=123)
bivae = BiVAECF(k=10)
models = [mf, pmf, bpr, bivae]

# define metrics to evaluate the models
metrics = [MAE(), RMSE(), Precision(k=10), Recall(k=10), NDCG(k=10), AUC(), MAP()]

# put it together in an experiment, voilà!
cornac.Experiment(eval_method=rs, models=models, metrics=metrics, user_based=True).run()

Expected behavior

The experiment should run successfully and output the results

dvquy13 avatar Aug 12 '24 12:08 dvquy13