0
votes

I have a csv file with this format:

id,category
1x,restaurant
1x,café
2y,café
2y,indian restaurant
3z,italian restaurant

and I want a sparse matrix which has for rows id, and for columns category.

for example:

    restaurant - café - indian - italian
1x   1          - 1    -    0   -   0
2y   0          - 1    -    1   -   0
3z   0          - 0    -    0   -   1

maybe it's necessary create a mapping to int key of matrix and the string of ids and categories.

I need this matrix to compute the cosine_similarity using from sklearn.metrics.pairwise import cosine_similarity.

Thanks!

EDIT:

I have written this code. mapping_categories.csv containts lines in this form:

0,cat1 1,cat2 2,cat3 ...

item_category_file_path contains the csv id,category.

This solution gives me a MemoryError.

mapping_categories = {}
with open("mapping_categories.csv") as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        mapping_categories[row[1]] = int(row[0].rstrip())

item_category = defaultdict(list)

with open(item_category_file_path) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['category'] in mapping_categories:
            item_category[row['business_id']].append(row['category'])
mapping_items = {}

item_number = 0
for item in item_category:
    mapping_items[item] = item_number
    item_number += 1

matrix_item_category = [0] * len(mapping_items)
for item in item_category:
    for category in item_category[item]:
        matrix_item_category[mapping_items[item]] = [0] * len(mapping_categories)
        matrix_item_category[mapping_items[item]][mapping_categories[category]] = 1

A_sparse = sparse.csr_matrix(matrix_item_category)

item_sim=cosine_similarity(A_sparse)

This solution gives me this error:

  File "/home/fily1212/.local/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 79, in __init__
    self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype)))
  File "/home/fily1212/.local/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 32, in __init__
    arg1 = arg1.asformat(self.format)
  File "/home/fily1212/.local/lib/python3.6/site-packages/scipy/sparse/base.py", line 287, in asformat
    return getattr(self, 'to' + format)()
  File "/home/fily1212/.local/lib/python3.6/site-packages/scipy/sparse/coo.py", line 342, in tocsr
    data = np.empty_like(self.data, dtype=upcast(self.dtype))
  File "/home/fily1212/.local/lib/python3.6/site-packages/scipy/sparse/sputils.py", line 51, in upcast
    raise TypeError('no supported conversion for types: %r' % (args,))
TypeError: no supported conversion for types: (dtype('O'),)

--

mapping_categories = {}
with open("mapping_categories.csv") as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        mapping_categories[row[1]] = int(row[0].rstrip())

item_category = defaultdict(list)

with open(item_category_file_path) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['category'] in mapping_categories:
            item_category[row['business_id']].append(row['category'])

mapping_items = {}

matrix_item_category = {}
item_number = 0
for item in item_category:
    mapping_items[item] = item_number
    for category in item_category[item]:
        matrix_item_category[item_number] = [0] * len(mapping_categories)
        matrix_item_category[item_number][mapping_categories[category]] = 1
    item_number += 1

A_sparse = sparse.csr_matrix(matrix_item_category)

item_sim=cosine_similarity(A_sparse)
1
so you want a sparse matrix which has for rows id, and for columns category? - ritlew

1 Answers

0
votes

I am not sure why you call your matrix "sparse." The way it is described and shown, it is dense.

Read the file into a pandas dataframe:

import pandas as pd
df = pd.read_csv("your_file_name", sep=",")

Add a dummy variable to the dataframe:

df['dummy'] = 1

Declare a new index based on both the id and category, convert the matrix from "tall" to "square" with unstack, and clean the missing values:

mtx = df.set_index(['id','category']).unstack().fillna(0).astype(int)

Finally, fix the column headers:

mtx.columns = mtx.columns.levels[1]
mtx
#category  café indian restaurant italian restaurant restaurant
#id                                                            
#1x           1                 0                  0          1
#2y           1                 1                  0          0
#3z           0                 0                  1          0