#python #machine-learning #xgboost #text-classification
Вопрос:
Я пытаюсь выполнить многоклассовую классификацию текста, используя ~9000 документов и 5 меток с помощью XGBoost. Я также пытаюсь использовать разделение 20/80 для обучения и тестирования, но не могу понять, как это сделать. Вот мой код после загрузки данных и библиотек:
new_sentence = []
for sentence in text_column:
text = re.sub("@S |https?:S|[^A-Za-z0-9] ",'',str(sentence).lower()).strip()
text = [wnl.lemmatize(i) for i in text.split ('') if i not in stop_words]
new_review.append(''.join(text))
return new_review
train['sentence'] = preprocess(train['sentence'])
test['sentence'] = preprocess(test['sentence'])
from sklearn.feature_extraction.text import CountVectorizer
# vectorizing the sentences
cv = CountVectorizer(binary = True) # implies that it indicates whether the word is present or not.
cv.fit(train['sentence']) # find all the unique words from the training set
train_x = cv.transform(train)
test_x = cv.transform(test)
# importing the relevant modules
import xgboost as xgb
xgb_train_labels = []
accepted_strings_half1 = {'location', 'service', 'price'}
accepted_strings_half2 = {'food', 'time'}
for topic in train['topic']:
if topic in accepted_strings_half1:
xgb_train_labels.append(1)
elif topic in accepted_strings_half2:
xgb_train_labels.append(0)
else:
xgb_train_labels.append(None)
xgb_test_labels = []
for topic in test['topic']:
if topic in accepted_strings_half1:
xgb_test_labels.append(1)
elif topic in accepted_strings_half2:
xgb_test_labels.append(0)
else:
xgb_test_labels.append(None)
# creating a variable for the new train and test sets
xgb_train = xgb.DMatrix(train_x, xgb_train_labels)
xgb_test = xgb.DMatrix(test_x, xgb_test_labels)
# Setting the Parameters of the Model
param = {'objective':'multi:softmax', 'num_class': 5 , 'eta': 0.75,
'max_depth': 50,}
# Training the Model
xgb_model = xgb.train(param, xgb_train, num_boost_round = 30)
# Predicting using the Model
y_pred = xgb_model.predict(xgb_test)
y_pred = np.where(np.array(y_pred) > 0.5, 1, 0) # converting them to 1/0’s
# Evaluation of Model
accuracy_score(xgb_test_labels, y_pred)
f1_score(xgb_test_labels, y_pred)
Я получаю эту ошибку при попытке запустить последнюю ячейку выше:
Отслеживание ошибок XGBoost (последний последний вызов) в () 3 ‘max_depth’: 50,} 4 # Обучение модели —-> 5 xgb_model = xgb.train(параметр, xgb_train, num_boost_round = 30) 6 # Прогнозирование с использованием модели 7 y_pred = xgb_model.прогноз(xgb_test)
3 кадров /usr/local/lib/python3.7/dist-packages/xgboost/core.py в check_call(в отставке) 174 «»» 175 если рэт != 0: —> 176 поднять XGBoostError(py_str(Либ.XGBGetLastError())) XGBoostError 177 178: [23:04:45] рабочих //в src/цели/multiclass_obj.КР:60: проверка не пройдена: предс.Размер() == (метод static_cast<size_t>(парам.num_class) * инфо.ярлыки.Размер()): SoftmaxMultiClassObj: размер метки размер и пред не соответствует трассировка стека:
Please let me know if there is anything I could do to fix this! Thank you.