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

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)

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:

c:\programdata\anaconda3\lib\site-packages\scipy\spatial\distance.py(695)correlation()

       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 10, 2019 in Python by sam
• 120 points
1,109 views

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, 2020 in Python by anonymous
• 220 points

edited May 18, 2020 by Gitika 6,230 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, 2020 by Kalgi 4,021 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, 2020 in Python by Gitika
• 65,770 points
10,309 views
0 votes
1 answer

ValueError: could not broadcast input array from shape (360,270,3) into shape (360,280,3)

Hi@akhtar, In the above error it shows could not ...READ MORE

answered Apr 9, 2020 in Python by MD
• 95,460 points
20,492 views
+1 vote
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, 2020 in Python by MD
• 95,460 points
9,776 views
+1 vote
1 answer

WindowsError: [Error 126] The specified module could not be found.

Hi@akhtar, You can download the shapely module in ...READ MORE

answered Jul 13, 2020 in Python by MD
• 95,460 points
1,320 views
+1 vote
1 answer

Can anyone help me with this error: TypeError: list indices must be integers or slices, not str

Hi, @Varshap  It’s a TypeError, which tells us ...READ MORE

answered Nov 5, 2020 in Python by anonymous
• 65,770 points
2,376 views
0 votes
1 answer

ERROR: Could not build wheels for line-profiler which use PEP 517 and cannot be installed directly.

Hi@akhtar, If you are trying to install with pip ...READ MORE

answered Nov 5, 2020 in Python by MD
• 95,460 points
3,635 views
0 votes
0 answers

ValueError: could not broadcast input array from shape (224,224,9) into shape (224,224)

img_shape = 224 test_data = [] test_labels = [] for ...READ MORE

Nov 6, 2020 in Python by Eyosiyas
• 120 points
1,648 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP