Python 机器学习 - Training/Testing 并将预测应用于新数据集

Python Machine Learning - Training/Testing and apply prediction to new dataset

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

数据集 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

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

数据集 2:无标签

text        to_be_predicted
orange      fruit
celery      vegetable
mango       fruit

许多 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()

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

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

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