我正在处理著名的 Kaggle 挑战“房价”。我想用 sklearn.linear_model LinearRegression 训练我的数据集
阅读以下文章后:https : //developers.google.com/machine-learning/crash-course/representation/feature-engineering
我编写了一个函数,将列车 DataFrame 中的所有字符串值转换为列表。例如,原始特征值可能看起来像这样 [Ex, Gd, Ta, Po],转换后它看起来像这样:[1,0,0,0] [0,1,0,0] [0, 0,1,0] [0,0,0,1]。
当我尝试训练我的数据时,出现以下错误:
回溯(最近一次调用):文件“C:/Users/Owner/PycharmProjects/HousePrices/main.py”,第 27 行,在 linereg.fit(train_df, target) 文件“C:\Users\Owner\PycharmProjects\HousePrices \venv\lib\site-packages\sklearn\linear_model\base.py”,第 458 行,适合 y_numeric=True,multi_output=True)文件“C:\Users\Owner\PycharmProjects\HousePrices\venv\lib\site-包\sklearn\utils\validation.py", line 756, in check_X_y estimator=estimator) 文件 "C:\Users\Owner\PycharmProjects\HousePrices\venv\lib\site-packages\sklearn\utils\validation.py",第 567 行,在 check_array array = array.astype(np.float64) ValueError 中:使用序列设置数组元素。
这只发生在我按照我的解释转换某些列时。
有没有办法用向量作为值来训练线性回归模型?
这是我的转换函数:
def feature_to_boolean_vector(df, feature_name, new_name):
vectors_list = [] #each tuple will represent an option
feature_options = df[feature_name].unique()
feature_options_length = len(feature_options)
# creating a list the size of feature_options_length, all 0's
list_to_be_vector = [0 for i in range(feature_options_length)]
for i in range(feature_options_length):
list_to_be_vector[i] = 1 # inserting 1 representing option number i
vectors_list.append(list_to_be_vector.copy())
list_to_be_vector[i] = 0
mapping = dict(zip(feature_options, vectors_list)) # dict from values to vectors
df[new_name] = df[feature_name].map(mapping)
df.drop([feature_name], axis=1, inplace=True)
这是我的火车尝试(预处理后):
linereg = LinearRegression()
linereg.fit(train_df, target)
先感谢您。
相关分类