0

When using scikit learn or other similar Python libraries, what's the difference between doing:

import sklearn.cluster as sk
model = sk.KMeans(n_clusters=n)

And

from sklearn.cluster import KMeans 
model = KMeans(n_clusters=n)

Is there any advantage to using one way over the other?

Alex Kinman
  • 2,437
  • 8
  • 32
  • 51
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a coding or tutorial service. This is covered well in the Python documentation and many texts, both hard-copy and on line. – Prune Dec 28 '16 at 18:43
  • 2
    As explained [here](https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function/187471) "*Importing the module doesn't waste anything; the module is always fully imported*" so there is no way to import *only* a specific thing from a module – Cory Kramer Dec 28 '16 at 18:44
  • 1
    @Prune from **how to ask**: "Examples: Good: Why does using float instead of int give me different results when all of my inputs are integers?" -- why is my question in a different category than the example? – Alex Kinman Dec 28 '16 at 18:47
  • I think this is a fine question. Sure, the issue is well-documented and there's a similar question on another SE site but it's also a well-worded question with concise and clear examples. – 2rs2ts Dec 28 '16 at 18:54
  • Good enough -- objection withdrawn. I'll leave my comment as a bad example with good correction. – Prune Dec 28 '16 at 19:03

1 Answers1

1

Well, in your first example, you've made the module sklearn.cluster accessible as sk and you can refer to its members accordingly. In your second example, you've only imported one member of sklearn.cluster, KMeans, so only that one is accessible. That's the difference.

As for advantages? Do whichever makes your code easier to read.

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • 2
    "*you've only imported one member ... so only that one is accessible*" I'd be careful with that wording. They've actually imported the *entire module*, it's just that only `kMeans` is *accessible* – Cory Kramer Dec 28 '16 at 18:45
  • It might be a matter of semantics. Yes, the whole module is loaded (as can be seen from `sys.modules`) but I was referring to the `import` keyword. – 2rs2ts Dec 28 '16 at 18:52