Subhadip
Subhadip

Reputation: 461

TypeError: unhashable type: 'numpy.ndarray' in Python

I am reading data from a dataset containing points in a plane. Each point has x and y co-ordinate.

with open('SJC324.txt') as f:
    data=[]
    for line in f:
        x,y=(line.strip('\n').split())
        data.append([int(x),int(y)])
    initialisation(data)

Then I have done K-medoid clustering on those points. I have stored the medoid points in a list. Then I shall check what are the points lying within a specific radius from the medoids. In this way I am calculating the coverage.

def initialisation(data):
    data=np.array(data)
    D=pairwise_distances(data,metric='euclidean')
    coverage=[]
    for i in range(20):
        covered_point=set()
        M, C = kmedoids.kMedoids(D, len(data)//15)
        medoid=data[M]
        for temp in medoid:
            for x in data:
                if check_within_radius(temp,x):
                    covered_point.add(x)
        coverage.append((len(covered_point)/len(data))*100)
    print(coverage)

Here I am checking what are the points are lying within a specific radius of those medoids.

def check_within_radius(temp,x):
    #temp is medoid point
    #x is any random point
    radius=10
    if (((temp[0]-x[0])**2) + ((temp[1]-x[1])**2))< radius*radius:
        return True
    else:
        return False

Now I am getting the following error.

<ipython-input-23-d04cdfb631a8> in initialisation(data)
     16             for x in data:
     17                 if check_within_radius(temp,x):
---> 18                     covered_point.add(x)
     19         coverage.append((len(covered_point)/len(data))*100)
     20     print(coverage)

TypeError: unhashable type: 'numpy.ndarray'

Upvotes: 1

Views: 5041

Answers (1)

Subhadip
Subhadip

Reputation: 461

You are trying to find the unique elements within the 2D list. You can modify your code a bit.

from collections import Counter

temp = Counter([tuple(x) for x in covered_point])
#Counter will count the frequency of each element(1D list) in a 2D list

z = [list(k) for k, v in temp.items() if v >= 1]
'''
 When one element(1D list) appears more than once in that 2D list you are
 taking that only  one time.
'''

coverage.append((len(z)/len(data))*100)

Upvotes: 1

Related Questions