Reputation: 81
I'm trying to execute the following python notebook:
Them I came to the part where I have to use the function 'compute_cluster_similarities'.
def compute_cluster_similarities(kwds, kwd2id, vectors, lbl2centroid):
kwd2cluster_sims = dict()
for kwd in kwds:
ix = kwd2id[kwd]
nvec = vectors[ix]
sims = []
for lbl, centroid in lbl2centroid.items():
cosine_sim = np.inner(nvec, centroid)
sims.append((lbl,cosine_sim))
sims = sorted(sims, key = lambda lbl,sim: -sim)
kwd2cluster_sims[kwd] = sims
if len(kwd2cluster_sims) % 1000 == 0:
print("%i computed out of %i" % (len(kwd2cluster_sims), len(all_kwds)))
return kwd2cluster_sims
And its returning the error:
TypeError: () missing 1 required positional argument: 'sim'
First of all, I'm still trying to understand this part of the lambda code. I learned what is the objective of the lambda instruction but couldn't understand what is the point of this line of code, like.. is it (implicity) returning 2 values (sims, key)?? What is being sorted?
I think that this error is ocurring due the Python 3, but even if this was executed on Python 2, it doesn't make sense to me. It's very confusing for me... How can I solve this error? And please, give me some explanation about what it's going on, not just the fix.
EDIT: I'm using pdb library to debug the code and I realized that this error was being returned by the 'sorted()' function. The original error is:
*** TypeError: 'function' object is not iterable
What I did:
cosine_sim = np.inner(nvec, centroid)
sims.append((lbl,cosine_sim))
import pdb ; pdb.set_trace();
sims = sorted(sims, key = lambda lbl,sim: -sim)
and them at the Pdb mode:
(Pdb) sims, key = lambda lbl,sim: -sim
*** TypeError: 'function' object is not iterable
Upvotes: 0
Views: 3937
Reputation: 26896
The function in the key
parameter of sorted
is fetched with the elements of the list, therefore it accepts only one parameter.
If you substitute:
key = lambda lbl,sim: -sim
with:
key=lambda x: -x[1]
It should work as you expect.
Refer to the documentation for more explanation of how to use sorted
and the key
parameter.
Upvotes: 1