python - 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
解决方案
许多 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()
推荐阅读
- java - Java 运算符优先级究竟是如何工作的?
- kubernetes - 具有 PVC 的 Kubernetes/Openshift pod 是否保留其集群名称和 IP?
- python - 当我打印清单上的项目时,我将如何对其进行编号?
- postgresql - Jhipster休眠序列不生成新ID
- sql - 在这种情况下,是否可以基于集合而不是游标循环?
- node.js - 使用 Node.js 中的 linux 命令删除和复制所有文件
- ejb-3.1 - EJB 计时器服务: WTRN0006W: 事务 xxxx 在 120 秒后超时
- javascript - Electron desktopCapturer.getSources().then 不是函数
- python-3.x - 根据行号检索文本
- razor - 导航栏下的固定标题