【发布时间】:2021-07-10 20:59:00
【问题描述】:
我正在使用 Scikit-learn 执行监督机器学习。我有两个数据集。第一个数据集包含具有 X 特征和 Y 标签的数据。第二个数据集仅包含 X 个特征,但没有 Y 标签。我可以成功地对训练/测试数据执行 LinearSVC 并获得测试数据集的 Y 标签。
现在,我想使用我为第一个数据集训练的模型来预测第二个数据集的标签。如何在 Scikit-learn 中使用从第一个数据集到第二个数据集(看不见的标签)的预训练模型?
我尝试的代码 sn-p: 以下来自 cmets 的更新代码:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
import pickle
# ----------- Dataset 1: for training ----------- #
# Sample data ONLY
some_text = ['Books are amazing',
'Harry potter book is awesome. It rocks',
'Nutrition is very important',
'Welcome to library, you can find as many book as you like',
'Food like brocolli has many advantages']
y_variable = [1,1,0,1,0]
# books = 1 : y label
# food = 0 : y label
df = pd.DataFrame({'text':some_text,
'y_variable': y_variable
})
# ------------- TFIDF process -------------#
tfidf = TfidfVectorizer()
features = tfidf.fit_transform(df['text']).toarray()
labels = df.y_variable
features.shape
# ------------- Build Model -------------#
model = LinearSVC()
X_train, X_test, y_train, y_test= train_test_split(features,
labels,
train_size=0.5,
random_state=0)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# Export model
pickle.dump(model, open('model.pkl', 'wb'))
# Read the Model
model_pre_trained = pickle.load(open('model.pkl','rb'))
# ----------- Dataset 2: UNSEEN DATASET ----------- #
some_text2 = ['Harry potter books are amazing',
'Gluten free diet is getting popular']
unseen_df = pd.DataFrame({'text':some_text2}) # Notice this doesn't have y_variable. This the is the data set I am trying to predict y_variable labels 1 or 0.
# This is where the ERROR occurs
X_unseen = tfidf.fit_transform(unseen_df['text']).toarray()
y_pred_unseen = model_pre_trained.predict(X_unseen) # error here:
# ValueError: X has 11 features per sample; expecting 26
print(X_unseen.shape) # prints (2, 11)
print(X_train.shape) # prints (2, 26)
# Looking for an output like this for UNSEEN data
# Looking for results after predicting unseen and no label data.
text y_variable
Harry potter books are amazing 1
Gluten free diet is getting popular 0
它不一定是我上面尝试的泡菜代码。我正在寻找是否有人有建议,或者是否有任何预构建功能可以从 scikit 进行预测?
【问题讨论】:
-
X_unseen 必须具有与 X_train 和 X_test 相同顺序的相同特征
-
我们训练模型,而不是数据集(编辑标题);问题显然与
tensorflow无关 - 请不要发送垃圾邮件无关标签(已删除)。
标签: python python-3.x machine-learning scikit-learn