NameError:未定义名称“ X”

时间:2019-06-24 14:39:36

标签: python scikit-learn data-science

我正在逐步解决这个多元回归问题,但是代码始于

section:#在网站https://towardsdatascience.com/what-makes-a-movie-hit-a-jackpot-learning-from-data-with-multiple-linear-regression-339f6c1a7022上使用一键编码处理分类变量

到目前为止,我已经运行了代码,但不适用于(X)

实际代码:

 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)

这是我得到的错误:

 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 个答案:

答案 0 :(得分:2)

您的代码不应该工作,因为您在该代码段之前遗漏了她写的40行代码。她之前已经定义了X。可以从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