0
$\begingroup$

I have googled and read something similar to the problem I have but I do not seem to know how to fix the error I got from this particular code:

import operator
def getNeighbors(movieID, K):
    distances = []
    for movie in movieDict:
        if (movie != movieID):
            dist = ComputeDistance(movieDict[movieID], movieDict[movie])
            distances.append((movie, dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(K):
        neighbors.append(distance[x][0])
    return neighbors

K = 10
avgRating = 0
neighbors = getNeighbors(1, K)
**ValueError:** operands could not be broadcast together with shapes (19,)(0,)

The full code:

import numpy as np
import pandas as pd
r_cols = ['user_id', 'movie_id', 'rating']
ratings = pd.read_csv('C:/Users/dell/Downloads/DataScience/DataScience-Python3/ml-100k/u.data', sep='\t', engine='python', names=r_cols, usecols=range(3))  # please enter your file path here. The file is u.data
print(ratings.head())   
movieProperties = ratings.groupby('movie_id').agg({'rating': [np.size, np.mean]})
print(movieProperties.head())

movieNumRatings = pd.DataFrame(movieProperties['rating']['size'])
movieNormalizedNumRatings = movieNumRatings.apply(lambda x: (x - np.min(x)) / (np.max(x) - np.min(x)))
print(movieNormalizedNumRatings.head())

movieDict = {}
with open('C:/Users/dell/Downloads/DataScience/DataScience-Python3/ml-100k/u.item') as f:     # The file is u.item
    temp = ''
    for line in f:
        fields = line.rstrip('\n').split('|')
        movieID = int(fields[0])
        name = fields[1]
        genres = fields[5:25]
        genres = map(int, genres)
        movieDict[movieID] = (name, genres, movieNormalizedNumRatings.loc[movieID].get('size'), movieProperties.loc[movieID].rating.get('mean'))

print(movieDict[1])

from scipy import spatial
def ComputeDistance(a, b):
    genresA = np.array(list(a[1]))
    genresB = np.array(list(b[1]))
    genreDistance = spatial.distance.cosine(genresA, genresB)
    popularityA = np.array(a[2])
    popularityB = np.array(b[2])
    popularityDistance = abs(popularityA - popularityB)
    return genreDistance + popularityDistance  

print(ComputeDistance(movieDict[2], movieDict[4])) 

import operator

def getNeighbors(movieID, K):
    distances = []
    for movie in movieDict:
        if (movie != movieID):
            dist = ComputeDistance(movieDict[movieID], movieDict[movie])
            distances.append((movie, dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(K):
        neighbors.append(distance[x][0])
    return neighbors

K = 10
avgRating = 0

neighbors = getNeighbors(1, K)
```
$\endgroup$
  • $\begingroup$ Please detail which line is raising the issue and add the full stack trace. Please also note that pure code questions belong to StackOverflow, where you could surely get better answers, and faster. $\endgroup$ – Romain Reboulleau Nov 8 at 6:22
  • $\begingroup$ @ Romain Reboulleau I just did that. You can check out the question on StackOverflow. It has the title "Operands Could not be Broadcast with Shapes (19,)(0,) — KNN". Thanks $\endgroup$ – Mr Prof Nov 9 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.