首页 > 解决方案 > Python 机器学习 - 训练/测试并将预测应用于新数据集

问题描述

我只对单个数据集拆分进行了培训和测试。我有一个监督学习问题:数据 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

标签: pythonscikit-learntrain-test-split

解决方案


许多 scikit-learn 监督分类器具有predict处理新数据的能力。

例如,查看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()

在此处输入图像描述


推荐阅读