1

It is very strange in Python that, I need specify the return vector and print them out. My original code is:

import scipy.cluster.vq as spk
result = spk.kmeans2(dataset, 5)
print result.label

or like this:

import scipy.cluster.vq as spk
print spk.kmeans2(dataset, 5).label

I got an error: AttributeError: 'tuple' object has no attribute 'label'

However, when I change the code to:

import scipy.cluster.vq as spk
code, label = spk.kmeans2(dataset, 5)
print label

The code works fine. So what is the problem?

2
  • umm... because it returns a tuple? Commented Dec 1, 2015 at 2:47
  • 1
    It is not weird, you are just unpacking the returned value. Also keep in mind that a function in Python can return multiple things which are actually wrapped up with a tuple. Commented Dec 1, 2015 at 2:59

1 Answer 1

2

The result is a tuple. A tuple can be accessed with index. So the right way to access the data will be

import scipy.cluster.vq as spa
print spk.kmeans2(dataset, 5)[0]  # for code
print spk.kmeans2(dataset, 5)[1]  # for label

That should work. Do read https://docs.python.org/2/tutorial/datastructures.html for more info

Sign up to request clarification or add additional context in comments.

2 Comments

That's not the right way. You processed the data twice! Tuple unpacking is a better option.
Thats right... Just an example to explain the concept of the positions of the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.