我只对单个数据集拆分进行过培训和测试。 我有一个受监督的学习问题:数据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
答案 0 :(得分:0)
许多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()
答案 1 :(得分:0)
在进行任何培训之前,您需要将分类特征转换为数值变量。否则,任何模型都无法处理这些数据。
要转换为数字特征,您将需要使用OneHotEncoder
:https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
接下来,由于您在训练集中有标签,因此需要有监督的学习。 此处更多内容:https://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html