Operands Could not be Broadcast with Shapes (19,)(0,) — KNN

0 votes

I am working on how to use KNN to predict a rating for a movie. I use a video and a book to teach myself how to go about it

I tried to run the code I found in the book but it gave me error message. I googled the error message so as to understand it and fix my problem but I don't think I know how to adapt the solutions to my problem. The code is given below:

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


movieProperties = ratings.groupby('movie_id').agg({'rating': [np.size, np.mean]})


movieNumRatings = pd.DataFrame(movieProperties['rating']['size'])

movieNormalizedNumRatings = movieNumRatings.apply(lambda x: (x - np.min(x)) / (np.max(x) - np.min(x)))


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'))


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))


    neighbors = []

    for x in range(K):


    return neighbors
K = 10
avgRating = 0

neighbors = getNeighbors(1, K)

I got this error message from PowerShell:

Traceback(most recent call last):

neighbors = getNeighbors(1, K)

dist = ComputeDistance(movieDict[movieID], movieDict[movie])

genreDistance = spatial.distance.cosine(genresA, genresB)

return correlation(u, v, w=w, centered=False)

uv = np.average(u*v, weights=w)

ValueError: operands could not be broadcast together with shape (19,)(0,)

I got this error message when I tried to debug the problem from ipython terminal:


       693        u = u - umu

       694        v = v - vmu

--->  695        uv = np.average(u*v, weights=w)

       696        uu = np.average(np.square(u), weights=w)

       697        vv = np.average(np.square(v), weights=w)

Nov 9, 2019 in Python by sam
• 120 points

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Python

+1 vote
0 answers

ValueError: operands could not be broadcast together with shapes (3,) (1000,)

This is the part of my code, why ...READ MORE

May 17 in Python by anonymous
• 220 points

edited May 18 by Gitika 366 views
0 votes
1 answer
+1 vote
0 answers

ValueError: could not broadcast input array from shape (2) into shape (5)

I was implementing gillespie algorithm and when ...READ MORE

Dec 23, 2019 in Python by anonymous
• 130 points

reshown Jan 13 by Kalgi 1,210 views
0 votes
1 answer

ValueError: could not broadcast input array from shape (4,1) into shape (4)

Hey @Giorgio, You can try this hope this ...READ MORE

answered Feb 18 in Python by Gitika
• 31,430 points
0 votes
1 answer
0 votes
1 answer

ImportError: DLL load failed: The specified module could not be found.

Hi@akhtar, You may get this error if you ...READ MORE

answered Jun 22 in Python by MD
• 33,090 points
0 votes
1 answer

Python error: No handlers could be found for logger “xhtml2pdf”

The only solution is to define a ...READ MORE

answered Sep 5, 2018 in Python by Priyaj
• 57,530 points
0 votes
1 answer

print(instance(0).id) TypeError: 'list' object is not callable

Hey @Suraj, For me its working fine. ...READ MORE

answered Jan 18, 2019 in Python by Priyaj
• 57,530 points
0 votes
3 answers
0 votes
3 answers

TypeError: Index(...) must be called with a collection of some kind, 'Email' was passed

It is not working because your code ...READ MORE

answered May 12 in Python by anonymous

edited May 13 by Gitika 17,653 views