NameError: name 'X' is not defined sklearn

Viewed 4472

I am working through this multiple regression problem with this walk through however the code that starts at

section : #Treating categorical variables with One-hot-encoding at website: https://towardsdatascience.com/what-makes-a-movie-hit-a-jackpot-learning-from-data-with-multiple-linear-regression-339f6c1a7022

I ran code up to this point but it doesn't work for (X)

Actual code:

 from sklearn import preprocessing
 le = preprocessing.LabelEncoder()


# LabelEncoder for a number of columns
class MultiColumnLabelEncoder:

 def __init__(self, columns = None):
    self.columns = columns # list of column to encode
    def fit(self, X, y=None):
    return self
    def transform(self, X):
    '''
    Transforms columns of X specified in self.columns using
    LabelEncoder(). If no columns specified, transforms all
    columns in X.
    '''

    output = X.copy()

    if self.columns is not None:
        for col in self.columns:
            output[col] = LabelEncoder().fit_transform(output[col])
    else:
        for colname, col in output.iteritems():
            output[colname] = LabelEncoder().fit_transform(col)

    return output
def fit_transform(self, X, y=None):
    return self.fit(X, y).transform(X)

  le = MultiColumnLabelEncoder()
  X_train_le = le.fit_transform(X)

Here is the error that I get:

 Traceback (most recent call last):

  File "<ipython-input-63-581cea150670>", line 34, in <module>
    X_train_le = le.fit_transform(X)

NameError: name 'X' is not defined
1 Answers

Your code shouldn't be able to work because you left out 40 lines of codes that she wrote before that snippet of codes. She has defined X earlier. The codes can be obtained from Github.

#importing the libraries
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import RFE
from sklearn.linear_model import RidgeCV, LassoCV, Ridge, Lasso
import statsmodels.api as sm
import pyreadr
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.metrics import explained_variance_score
from sklearn import metrics
from sklearn.preprocessing import StandardScaler

result = pyreadr.read_r('Movies.RData')# also works for Rds
print(result.keys())
df = pd.DataFrame(result['movies'], columns=result['movies'].keys() )
df.shape

df.shape[0]
df.set_index("title", inplace=True) #setting the index name
df_1 = df.loc[:, ['imdb_rating','genre', 'runtime', 'best_pic_nom',
                  'top200_box', 'director', 'actor1']]

#Let's also check the column-wise distribution of null values
print(df_1.isnull().values.sum())
print(df_1.isnull().sum())

#Dropping missing values from my dataset
df_1.dropna(how='any', inplace=True)
print(df_1.isnull().values.sum()) #checking for missing values after the dropna()

#Splitting for 2 matrices: independent variables used for prediction and dependent variables (that is predicted)
X = df_1.drop(["imdb_rating", 'runtime'], axis = 1)   #Feature Matrix
y = df_1["imdb_rating"] #Dependent Variables
Related