【问题标题】:Python Machine Learning - Training/Testing and apply prediction to new datasetPython 机器学习 - 训练/测试并将预测应用于新数据集
【发布时间】:2020-02-03 00:41:24
【问题描述】:

我只对单个数据集拆分进行了训练和测试。 我有一个监督学习问题:数据 1 训练/测试和数据 2:没有标签。我正在使用熊猫数据框。

数据集 1:监督

text        y_variable
apple       fruit
orange      fruit
celery      vegetable
mango       fruit

数据集 2:没有标签

text        to_be_predicted
orange      ?
celery      ?
mango       ?

我正在使用 scikit 学习:

X = df['text']
y = df['y_variable']

X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2

这会将现有数据框拆分为训练和测试。如何训练/测试第一个数据集 1 并将其应用于第二个数据集?机器学习。

数据集 2:没有标签

text        to_be_predicted
orange      fruit
celery      vegetable
mango       fruit

【问题讨论】:

  • 您是否正在尝试训练有监督方法并作为无监督方法进行测试? + 你没有关于每个项目的额外信息吗?例如....形状/重量/颜色....??您的 df 只有 2 列?

标签: python scikit-learn train-test-split


【解决方案1】:

许多 scikit-learn 监督分类器能够predict 处理新数据。

例如,查看documentation 的 K 最近邻:

knn.predict(new_data) # will predict classes for new data

更新

在预测类时,根据新数据,只需指定新的X。为了更好地描述,这里有一个较长的代码版本:

import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

# make some example data
X, y = make_blobs(n_samples = 100, n_features = 2, 
                  centers = 2, random_state = 123)

# fit supervised KNN classifier
knn = KNeighborsClassifier()
knn.fit(X, y) 

# create 50 new data points
# with the same number of features as the training set
new_data = np.random.randn(50, 2)

# predict new labels
new_labels = knn.predict(new_data)

# plot training clusters
plt.plot(X[y== 1, 0], 
         X[y==1,1], 
         "C1o", label = "training cluster 1")
plt.plot(X[y== 0, 0], 
         X[y==0,1], 
         "C0o", label = "training custer 2")

# plot predictions on new data
plt.plot(new_data[new_labels== 1, 0], 
         new_data[new_labels==1,1], 
         "ro", label = "new data assigned to cluster 1")
plt.plot(new_data[new_labels== 0, 0], 
         new_data[new_labels==0,1], 
         "bo", label = "new data assigned to cluster 2")
plt.legend()

【讨论】:

  • 我是否必须指定 y 变量列是什么?
  • 在预测新数据时不必指定y。我已经更新了我的代码以提供更好的示例。
【解决方案2】:

在进行任何训练之前,您需要将分类特征转换为数值变量。否则,任何模型都无法处理这些数据。

要转换为数字特征,您需要使用 OneHotEncoder: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

接下来,由于您在训练集中有标签,因此您需要监督学习。 更多内容:https://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 2020-02-21
    • 2015-12-21
    • 2019-07-03
    • 2012-03-27
    • 2020-07-01
    • 2019-04-20
    • 2019-07-15
    相关资源
    最近更新 更多