【问题标题】:Predicting numerical features based on string features using sk-learn使用 sk-learn 基于字符串特征预测数值特征
【发布时间】:2021-01-12 15:57:07
【问题描述】:

我正在尝试预测“Full_Time_Home_Goals”列(功能)。 我遵循了Kaggle 示例。该代码适用于我的示例中的不同维度(测试数据中的 419 行和训练数据中的 892 行)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# %matplotlib inline

# Set option to display all the rows and columns in the dataset. If there are more rows, adjust number accordingly.
pd.set_option('display.max_rows', 5000)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

# Files
data_train = pd.read_csv(r"C:\Users\harsh\Documents\My Dream\Desktop\Machine Learning\Attempt 3\train.csv")
data_test = pd.read_csv(r"C:\Users\harsh\Documents\My Dream\Desktop\Machine Learning\Attempt 3\test.csv")


columns = ['Id', 'HomeTeam', 'AwayTeam', 'Full_Time_Home_Goals']
col = ['Id', 'HomeTeam', 'AwayTeam']
data_test = data_test[col]
data_train = data_train[columns]

data_train = data_train.dropna()
data_test = data_test.dropna()

data_train['Full_Time_Home_Goals'] = data_train['Full_Time_Home_Goals'].astype(int)

from sklearn import preprocessing


def encode_features(df_train, df_test):
    features = ['HomeTeam', 'AwayTeam']
    df_combined = pd.concat([df_train[features], df_test[features]])

    for feature in features:
        le = preprocessing.LabelEncoder()
        le = le.fit(df_combined[feature])
        df_train[feature] = le.transform(df_train[feature])
        df_test[feature] = le.transform(df_test[feature])
    return df_train, df_test


data_train, data_test = encode_features(data_train, data_test)
print(data_train.head())
print(data_test.head())

# X_all would contain all columns required for prediction and y_all would have that one columns we want to predict

X_all = data_train

y_all = data_train['Full_Time_Home_Goals']

from sklearn.model_selection import train_test_split

num_test = 0.20  # 80-20 split
X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=num_test, random_state=23)

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import make_scorer, accuracy_score
from sklearn.model_selection import GridSearchCV

# Using Random Forest and using parameters that we defined

clf = RandomForestClassifier()

parameters = {'n_estimators': [4, 6, 9],
              'max_features': ['log2', 'sqrt', 'auto'],
              'criterion': ['entropy', 'gini'],
              'max_depth': [2, 3, 5, 10],
              'min_samples_split': [2, 3, 5],
              'min_samples_leaf': [1, 5, 8]
              }

acc_scorer = make_scorer(accuracy_score)

grid_obj = GridSearchCV(clf, parameters, scoring=acc_scorer)
grid_obj = grid_obj.fit(X_train, y_train)

clf = grid_obj.best_estimator_

clf.fit(X_train, y_train)

predictions = clf.predict(X_test)

我得到的错误是:

  1. 代码原样:

    Traceback(最近一次调用最后一次): 文件“C:/Users/harsh/PycharmProjects/Kaggle-Machine Learning from Start to Finish with Scikit-Learn/EPL Predicting.py”,第 98 行,在 预测 = clf.predict(data_test.drop('Id', axis=1)) 文件“C:\Users\harsh\PycharmProjects\GitHub\venv\lib\site-packages\sklearn\ensemble_forest.py”, 第 629 行,在预测中 ValueError:模型的特征数量必须与输入匹配。模型 n_features 为 4,输入 n_features 为 2

  2. 将代码从predictions = clf.predict(data_test.drop('Id', axis=1))to predictions = clf.predict(X_test)更改为:

     raise ValueError(msg) ValueError: array length 37921 does not match index length 380
    

我该如何解决这个问题?

My datasets used can be found here

【问题讨论】:

  • 请注意,任何出现在错误之后的代码都与问题无关(从不执行)并且不应包含在此处,因为它只会造成不必要的混乱;注释掉的代码(已编辑)也是如此。
  • 使用X_all = data_train,您可能已经将您的标签列'Full_Time_Home_Goals'留在了功能中。
  • 尝试将X_all = data_train; y_all = data_train['Full_Time_Home_Goals'] 更改为y_all = data_train['Full_Time_Home_Goals']; X_all = data_train.drop(['Full_Time_Home_Goals'],axis=1) 看看是否有帮助。还要考虑上述关于削减代码的建议

标签: python scikit-learn encoder


【解决方案1】:

以下是您的经过测试且可以正常工作的代码:

data_train = pd.read_csv(r"train.csv")
data_test = pd.read_csv(r"test.csv")


columns = ['Id', 'HomeTeam', 'AwayTeam', 'Full_Time_Home_Goals']
col = ['Id', 'HomeTeam', 'AwayTeam']
data_test = data_test[col]
data_train = data_train[columns]

data_train = data_train.dropna()
data_test = data_test.dropna()

data_train['Full_Time_Home_Goals'] = data_train['Full_Time_Home_Goals'].astype(int)

from sklearn import preprocessing


def encode_features(df_train, df_test):
    features = ['HomeTeam', 'AwayTeam']
    df_combined = pd.concat([df_train[features], df_test[features]])

    for feature in features:
        le = preprocessing.LabelEncoder()
        le = le.fit(df_combined[feature])
        df_train[feature] = le.transform(df_train[feature])
        df_test[feature] = le.transform(df_test[feature])
    return df_train, df_test


data_train, data_test = encode_features(data_train, data_test)
print(data_train.head())
print(data_test.head())

# X_all would contain all columns required for prediction and y_all would have that one columns we want to predict

y_all = data_train['Full_Time_Home_Goals']
X_all = data_train.drop(['Full_Time_Home_Goals'], axis=1)

from sklearn.model_selection import train_test_split

num_test = 0.20  # 80-20 split
X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=num_test, random_state=23)

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import make_scorer, accuracy_score
from sklearn.model_selection import GridSearchCV

# Using Random Forest and using parameters that we defined

clf = RandomForestClassifier()

parameters = {'n_estimators': [4, 6, 9],
              'max_features': ['log2', 'sqrt', 'auto'],
              'criterion': ['entropy', 'gini'],
              'max_depth': [2, 3, 5, 10],
              'min_samples_split': [2, 3, 5],
              'min_samples_leaf': [1, 5, 8]
              }

acc_scorer = make_scorer(accuracy_score)

grid_obj = GridSearchCV(clf, parameters, scoring=acc_scorer)
grid_obj = grid_obj.fit(X_train, y_train)

clf = grid_obj.best_estimator_

clf.fit(X_train, y_train)

predictions = clf.predict(X_test)

print(accuracy_score(y_test, predictions))

ids = data_test['Id']
predictions = clf.predict(data_test)

df_preds = pd.DataFrame({"id":ids, "predictions":predictions})
df_preds

   Id  HomeTeam  AwayTeam  Full_Time_Home_Goals
0   1        55       440                     3
1   2       158       493                     2
2   3       178       745                     1
3   4       185       410                     1
4   5       249        57                     2
       Id  HomeTeam  AwayTeam
0  190748       284        54
1  190749       124       441
2  190750       446        57
3  190751       185       637
4  190752       749       482
0.33213786556261704
id  predictions
0   190748  1
1   190749  1
2   190750  1
3   190751  1
4   190752  1
... ... ...
375 191123  1
376 191124  1
377 191125  1
378 191126  1
379 191127  1
380 rows × 2 columns

【讨论】:

  • 这行得通!我终于有输出了!呸!百万感谢谢尔盖。我绕圈子跑了这么久才到这里!进一步显然超出了问题的范围,但是,我注意到所有预测值都是 1。您不应该拥有所有相同的值,对吧?你认为我在这里缺少什么?
  • 您的模型的准确度是 0.33,并且正如您所注意到的,所有预测都是 1,这表明存在问题。您可能希望根据基线或纯猜测多数类检查此准确性。无论如何,对您的问题的简单回答可能是(1)找到更好的模型(2)使模型可以学习更多的特征。我将从第二个开始。这些建议基于结果确实是可学习的假设。
  • 当我引入包含浮动的功能时,我得到了TypeError: Encoders require their input to be uniformly strings or numbers. Got ['float', 'str'] 和TypeError: '<' not supported between instances of 'float' and 'str' 我该如何克服这个问题?示例数据:主队客队 FTHG B365H B365D B365A B365>2.5 B365
  • 我认为一个好的起点是文档(或至少是错误消息)。您的encode_features 函数,特别是LabelEncoder,要求特征是字符串或整数。如果您计划通过模型提供浮点数,则需要 (1) 分离浮点数和字符串 (2) 使用 func 对字符串进行编码,(3) 连接浮点数 (4) 将数据馈送到模型。您需要确保您对训练数据集和测试数据集所做的操作之间的一致性。
  • 有没有可以做这种预测的库(无监督)?张量流还是其他?你能给我指个方向吗?
猜你喜欢
相关资源
最近更新 更多
热门标签