How to create csr_matrix rating in scipy?

I have a csv file in this format:

userId  movieId rating  timestamp
1     31      2.5   1260759144
2     10      4     835355493
3     1197    5     1298932770
4     10      4     949810645

I want to build a sparse matrix with rows as userId and columns as movieID. I saved all the data as a dictionary with the name "column", where the ['user'] column contains user identifiers, the ['movie'] column has movie identifiers, and the ['ratings'] column has ratings as follows:

f = open('ratings.csv','rb')
reader = csv.reader(f)
headers = ['user','movie','rating','timestamp']
column = {}
for h in headers:
    column[h] = []
for row in reader:
    for h, v in zip(headers, row):
        column[h].append(float(v))

When I call a sparse matrix function as follows:

mat = scipy.sparse.csr_matrix((column['rating'],(column['user'],column['movie'])))

I get "TypeError: invalid form"

Please, help

+4
source share
2 answers
scipy.sparse.csr_matrix([column['rating'],column['user'],column['movie']])

You had a tuple consisting of a 1xn-dimensional list and a 2x-dimensional list that would not work.

P.S.: Pandas:-) (http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html). :

import pandas as pd

# Setup a dataframe from the CSV and make it sparse
df = pd.read_csv('ratings.csv')
df = df.to_sparse(fill_value=0)
print(df.head())
+1

:

df = pd.read_csv('f:\\train.csv', usecols=[0, 1, 2], names=['userId ', 
                   'movieID', 'ratings'], skiprows=1)
from scipy.sparse import csr_matrix
utility_csr = csr_matrix((df.ratings, (df.userId , df.movieID)))
0

Source: https://habr.com/ru/post/1660678/


All Articles