Import Only Work Inside Python Function
<p><strong>Background Info:</strong> I'm developing a model with scikit-learn. I'm splitting the data into separate training and testing sets using the sklearn.cross_validation module, as shown below:</p>

<pre><code>def train_test_split(input_data):
       from sklearn.cross_validation import train_test_split

        ### STEP 1: Separate y variable and remove from X
       y = input_data['price']
       X = input_data.copy()
       X.drop('price', axis=1, inplace=True)

        ### STEP 2: Split into training &amp; test sets
       X_train, X_test, y_train, y_test =\ 
                        train_test_split(X, y, test_size=0.2, random_state=0)
       return X_train, X_test, y_train, y_test
</code></pre>

<p><strong>My Question:</strong> When I try to import the sklearn.cross_validation module outside of my function, like so, I get the following error:</p>

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

def train_test_split(input_data):
       ### STEP 1: Separate y variable and remove from X
       y = input_data['price']
       X = input_data.copy()
       X.drop('price', axis=1, inplace=True)

       ### STEP 2: Split into training &amp; test sets
       X_train, X_test, y_train, y_test =\ 
                        train_test_split(X, y, test_size=0.2, random_state=0)
       return X_train, X_test, y_train, y_test
</code></pre>

<p><strong>Error:</strong></p>

<pre><code>TypeError: train_test_split() got an unexpected keyword argument 'test_size'
</code></pre>

<p>Any idea why?</p>

<p>You are importing the function <code>train_test_split</code> from <code>sklear.cross_validation</code> and then overriding the name with your local function <code>train_test_split</code>.</p>

<p>Try:</p>

<pre><code>from sklearn.cross_validation import train_test_split as sk_train_test_split

def train_test_split(input_data):
       ### STEP 1: Separate y variable and remove from X
       y = input_data['price']
       X = input_data.copy()
       X.drop('price', axis=1, inplace=True)

       ### STEP 2: Split into training &amp; test sets
       X_train, X_test, y_train, y_test =\ 
                        sk_train_test_split(X, y, test_size=0.2, random_state=0)  # use the imported function instead of local one
       return X_train, X_test, y_train, y_test
</code></pre>

python scikit-learn python-import