Long DF to CSR Conversion
Perhaps this is a basic question but I'm hoping someone might be able to help:
I'm trying to turn a very long data frame (user_id, item_id, value) into a sparse CSR.
I was able to do this on a smaller dataset by using pivot_table functions, something like:
df_wide = df_long.pivot_table(index='cid',columns='tinid',values='value',fill_value = 0,aggfunc=np.max)
Then run this "wide" df into the scipy sparse csr function, i.e.:
csr = scipy.sparse.csr_matrix(df_wide.values)
However this breaks when I get a very large dataset, I get int32 overflow. I.e.:
df_wide = df_long.pivot_table(index='user_id',columns='item_id',values='value',fill_value = 0,aggfunc=np.max)
ValueError: Unstacked DataFrame is too big, causing int32 overflow
(Full traceback):
Traceback (most recent call last):
File "<ipython-input-36-aab20a5e0c6e>", line 1, in <module>
df_wide = df_long.pivot_table(index='user_id',columns='item_id',values='value',fill_value = 0,aggfunc=np.max)
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\frame.py", line 6070, in pivot_table
return pivot_table(
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 132, in pivot_table
table = agged.unstack(to_unstack)
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\frame.py", line 6386, in unstack
return unstack(self, level, fill_value)
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 408, in unstack
return _unstack_frame(obj, level, fill_value=fill_value)
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 432, in _unstack_frame
unstacker = _Unstacker(
File "C:\Users\...\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 138, in __init__
raise ValueError("Unstacked DataFrame is too big, causing int32 overflow")
ValueError: Unstacked DataFrame is too big, causing int32 overflow
I'll be using something like a 4Mx4M matrix. I know this is possible because I see lots of other users using very large datasets. I also have tried to make use of a AWS Sagemaker algorithm which uses this package as its base, and its input is only the long, 2/3 column CSV.
Can anyone provide any insight on how to efficiently create the CSR and/or COO from a long df?
Thank you!
A good way of creating the sparse matrix from a df is shown in detail in the article here -> A Gentle Introduction to Recommender Systems with Implicit Feedback
Copied from the article:
customers = list(np.sort(grouped_purchased.CustomerID.unique())) # Get our unique customers
products = list(grouped_purchased.StockCode.unique()) # Get our unique products that were purchased
quantity = list(grouped_purchased.Quantity) # All of our purchases
rows = grouped_purchased.CustomerID.astype('category', categories = customers).cat.codes
# Get the associated row indices
cols = grouped_purchased.StockCode.astype('category', categories = products).cat.codes
# Get the associated column indices
purchases_sparse = sparse.csr_matrix((quantity, (rows, cols)), shape=(len(customers), len(products)))
I use this way to avoid the pivot, hope it helps.
A good way of creating the sparse matrix from a df is shown in detail in the article here -> A Gentle Introduction to Recommender Systems with Implicit Feedback
Copied from the article:
customers = list(np.sort(grouped_purchased.CustomerID.unique())) # Get our unique customers products = list(grouped_purchased.StockCode.unique()) # Get our unique products that were purchased quantity = list(grouped_purchased.Quantity) # All of our purchases rows = grouped_purchased.CustomerID.astype('category', categories = customers).cat.codes # Get the associated row indices cols = grouped_purchased.StockCode.astype('category', categories = products).cat.codes # Get the associated column indices purchases_sparse = sparse.csr_matrix((quantity, (rows, cols)), shape=(len(customers), len(products)))I use this way to avoid the pivot, hope it helps.
Hi, @ltsaprounis Can you please explain, why the conversion to categorical type is actually needed for rows and cols when the source data type is often integer? What's the purpose of this conversion in relation to further processing? What would happen if I hadn't converted the user/item columns to category type? It's really weird.
Thankx!
A good way of creating the sparse matrix from a df is shown in detail in the article here -> A Gentle Introduction to Recommender Systems with Implicit Feedback Copied from the article:
customers = list(np.sort(grouped_purchased.CustomerID.unique())) # Get our unique customers products = list(grouped_purchased.StockCode.unique()) # Get our unique products that were purchased quantity = list(grouped_purchased.Quantity) # All of our purchases rows = grouped_purchased.CustomerID.astype('category', categories = customers).cat.codes # Get the associated row indices cols = grouped_purchased.StockCode.astype('category', categories = products).cat.codes # Get the associated column indices purchases_sparse = sparse.csr_matrix((quantity, (rows, cols)), shape=(len(customers), len(products)))I use this way to avoid the pivot, hope it helps.
Hi, @ltsaprounis Can you please explain, why the conversion to categorical type is actually needed for
rowsandcolswhen the source data type is often integer? What's the purpose of this conversion in relation to further processing? What would happen if I hadn't converted the user/item columns to category type? It's really weird.Thankx!
@miro-mlynarik - If your source data is integers from 1 to N with no gaps, I too don't see the reason to convert to categorical.
If you try this I suggest you test that the resulting matrix is as you would expect by checking that the values of each matrix element are what you would expect based on the row and column indexes.
CSR (Condensed Sparse Row) matrix and many other sparse matrix data structures don't support 3D tensor. https://docs.scipy.org/doc/scipy/reference/sparse.html
One solution is to create a CSR for each category.
In my experiences, for a single machine, split DF into n DFs of (1/n) size, and iterate DF using
DF.itertuple() was the fastest to build col, row using Cython or numba.
@ltsaprounis I think @miro-mlynarik may like to divide matrices by interaction type.