iPython (python 2) - ImportError: No module named model_selection
<p>iPython Notebook
Python 2</p>

<p>Complaining about this line:</p>

<pre><code>from sklearn.model_selection import train_test_split
</code></pre>

<p>Why isn't model selection working?</p>

<p>In order to remedy this issue, you need to first find out if you are importing the actual <code>sklearn</code> package, and not just some script with the name <code>sklearn.py</code> saved somewhere in your working directory. The way Python imports modules is somewhat similar to the way it finds variables in its namespace (<code>Local</code>, <code>Enclosed</code>, <code>Global</code>, <code>Built-in</code>). In this case, Python will start importing module by first looking in the current directory and then the <code>site-packages</code>. If it looks in the current working directory and finds a python script with the same name as the module you are trying to import, then it will import that script instead of the actual module.</p>

<p>You can usually find out whether or not the actual module is imported by checking its <code>__file__</code> or <code>__path__</code> attribute:</p>

<pre><code>import sklearn

print(sklearn.__file__)
print(sklearn.__path__)
</code></pre>

<p>Reviewing the output of those print statements will tell you whether the imported package is the module you are after, or just some script lying somewhere in your working directory. If, in case, the output does not point to the <code>site-packages</code> of your Python version then you have imported some script somewhere that's not the module itself. Your quick fix would be to exit the console first, rename the <code>.py</code> script and its compiled version (the <code>.pyc</code> file) and go back to your console and try again.</p>

<p>However, if the output points to your python version's site-packages, then there is something wrong with how the package was installed in the first place. In which case, you will probably need to update or reinstall it.</p>

<p>Particular to this, it turns out that the issue is with the version of <code>sklearn</code> you are using; because the <code>model_selection</code> module in <code>sklearn</code> is available in versions <code>0.18+</code>. If you're using a version number (<code>sklearn.__version__</code>) lower than <code>0.18</code>, then you will have to use the old <code>cross_validation</code> module instead of the <code>model_selection</code> module:</p>

<pre><code>from sklearn.cross_validation import train_test_split
</code></pre>

<p>You can also just upgrade to the latest version of the package with your preferred package management system.</p>

<p>I hope this is helpful.</p>

python scikit-learn ipython sklearn-pandas