joelgrus / data-science-from-scratch

code for Data Science From Scratch book
MIT License
8.63k stars 4.5k forks source link

TypeError: unsupported operand type(s) for -: 'dict' and 'dict' #34

Open youcc opened 7 years ago

youcc commented 7 years ago

While running the code below by following the example in Chapter 19 Clustering,

random.seed(0) # so you get the same results as me
clusterer = KMeans(3)
clusterer.train(inputs)
print clusterer.means

I got this error message, "TypeError:unsupported operand type(s) for -: 'dict' and 'dict'".


/repo/data-science-from-scratch/code/linear_algebra.py in squared_distance(v, w)
     44 
     45 def squared_distance(v, w):
---> 46     return sum_of_squares(vector_subtract(v, w))
     47 
     48 def distance(v, w):

/repo/data-science-from-scratch/code/linear_algebra.py in vector_subtract(v, w)
     17 def vector_subtract(v, w):
     18     """subtracts two vectors componentwise"""
---> 19     return [v_i - w_i for v_i, w_i in zip(v,w)]
     20 
     21 def vector_sum(vectors):

TypeError: unsupported operand type(s) for -: 'dict' and 'dict'

Could you help me with this issue?

Thanks

youcc commented 7 years ago

I figured out that you used a difference "inputs" data in this Chapter than the inputs data in Chapter 17 on page 206. I came up my "inputs" data below according to Figure 19-1. It works fine.

inputs = [(-50, 0),
         (-49, 16),
         (-47, 5),
         (-42, 8),
         (-34, 0),
         (-26, -11),
         (-22, -17),
         (-18, -12),
         (-17, -5),
         (-14, -7),
         (-13, -20),
         (-10, -11),
         (-10, -5),
         (-8, -17),
         (10, 16),
         (12, 14),
         (20, 30),
         (21, 25),
         (22, 23),
         (27, 15)]