【问题标题】:ValueError: could not convert string to float - machine learningValueError:无法将字符串转换为浮点数 - 机器学习
【发布时间】:2019-11-07 22:59:56
【问题描述】:

我正在开展一个机器学习项目,以确定 PCAP 是否是攻击,我必须处理 PCAP 文件并创建模型,然后进行预测。 我的部分代码是这样的:

train['is_train'] = np.random.uniform(0, 1, len(train)) <= .75
Train, Validate = train[train['is_train']==True], train[train['is_train']==False]
features = list(set(list(dataset.columns))-set(ID_col)-set(target_col)-set(other_col))

x_train = Train[list(features)].values
y_train = Train["class"].values
x_validate = Validate[list(features)].values
y_validate = Validate["class"].values
x_test = test[list(features)].values


random.seed(100)
rf = RandomForestClassifier(n_estimators=1000)
rf.fit(x_train, y_train)

这就是我的 x_train 列表包含的内容:

[['172.27.224.250' 16 'TCP' ... 1532299481617 60 54200]
 ['172.27.224.251' 24 'TCP' ... 1532299483068 60 502]
 ['172.27.224.251' 24 'TCP' ... 1532299483069 60 502]
 ...
 ['172.27.224.251' 24 'TCP' ... 1532301279315 60 502]
 ['172.27.224.250' 16 'TCP' ... 1532301279324 60 49713]
 ['172.27.224.250' 24 'TCP' ... 1532301279335 66 49713]]

我在rf.fit(x_train, y_train) 中收到错误ValueError: could not convert string to float: '172.27.224.250'

我应该使用哪个分类器以及如何解决这个问题?

【问题讨论】:

  • 那些被称为分类变量。在您的用例中,我建议使用sklearn.preprocessor.OrdinalEncoder 将它们转换为整数编码数组,或者使用完全不同的分类器,例如默认情况下可以处理此类变量的CatBoostClassifier

标签: python machine-learning scikit-learn


【解决方案1】:

您需要将分类特征编码为数值,很少有像Label EncodingOne Hot Encoding 这样的技术,它们是sklearn.preprocessing 模块的一部分,可让您进行编码。因此,首先确定您的训练集中的分类列,并按照上述链接中的说明进行虚拟编码,然后应用.fit() 方法。

更多实现细节见Label encoder vs one hot encoder

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 2019-08-31
    • 1970-01-01
    • 2019-03-23
    • 2018-06-13
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多