Reputation: 11
I am following an online tutorial to learn ML and I tried to compile the code but keep getting the same error. I am using the latest version of the python and all the other libraries.
Code
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
###### helper functions. Use them when needed #######
def get_title_from_index(index):
return df[df.index == index]["title"].values[0]
def get_index_from_title(title):
return df[df.title == title]["index"].values[0]
##################################################
##Step 1: Read CSV File
df = pd.read_csv("test.csv")
##print (df.columns)
##Step 2: Select Features
features = ['keywords','cast','genres','director']
##Step 3: Create a column in DF which combines all selected features
for feature in features:
df[feature] = df[feature].fillna('')
def combine_features(row):
try:
return row['keywords'] +" "+row['cast']+" "+row["genres"]+" "+row["director"]
except:
print ("Error:", row)
df["combined_features"] = df.apply(combine_features,axis=1)
#print "Combined Features:", df["combined_features"].head()
print(combine_features)
##Step 4: Create count matrix from this new combined column
cv = CountVectorizer()
count_matrix = cv.fit_transform(df["combined_features"])
##Step 5: Compute the Cosine Similarity based on the count_matrix
cosine_sim = cosine_similarity(count_matrix)
movie_user_likes = "Avatar"
## Step 6: Get index of this movie from its title
movie_index = get_index_from_title(movie_user_likes)
print(movie_index)
print(get_index_from_title)
similar_movies = list(enumerate(cosine_sim[movie_index]))
## Step 7: Get a list of similar movies in descending order of similarity score
sorted_similar_movies = sorted(similar_movies,key=lambda x:x[1],reverse=True)
## Step 8: Print titles of first 50 movies
i=0
for element in sorted_similar_movies:
print (get_title_from_index(element[0]))
i=i+1
if i>50:
break
Error:
<function get_index_from_title at 0x7f8ed49e1d30>
Traceback (most recent call last):
File "/Applications/XAMPP/xamppfiles/htdocs/movierecommender/movie_recommender.py", line 46, in <module>
similar_movies = list(enumerate(cosine_sim[movie_index]))
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
As far as I understand the issue that cosine_sim is a float but it is expecting an integer. I have tried to cast similar_movies, movie_index and cosine_sim as int but it didn't work.
Any ideas?
Versions being used: Python: 3.9.1 Numphy: 1.19.4 matplotlib: 3.3.3 Pandas: 1.1.5 scikit-learn: 0.23.2 jupyter: 1.0.0 gym: 0.17.3 opencv-python: 4.4.0.46
Upvotes: 0
Views: 138
Reputation: 990
movie_index - must be an integer, but it is not. int(movie_index) - may help, in other case the problem with "movie_index" in "get_index_from_title" function.
Upvotes: 1