twitter_train_df = csv_loader('sentiment-train.csv') twitter_test_df = csv_loader('sentiment-test.csv')from sklearn.svm import SVC from sklearn.feature_extraction.text import TfidfVectorizer # 使用 TfidfVectorizer 对文本进行特征提取,并转换为 TF-IDF 矩阵 vectorizer = TfidfVectorizer() twitter_train_X = vectorizer.fit_transform(twitter_train_df['text']) twitter_test_X = vectorizer.transform(twitter_test_df['text']) twitter_train_y = twitter_train_df['sentiment'] twitter_test_y = twitter_test_df['sentiment'] # 使用 SVM 进行分类 clf = SVC(kernel='linear') clf.fit(twitter_train_X, twitter_train_y) # 打印模型在测试集上的准确率 accuracy = clf.score(twitter_test_X, twitter_test_y) print("The accuracy of the trained classifier is {:.2f}%".format(accuracy * 100))可以帮我把这段代码换成xgboost的吗
时间: 2023-12-24 18:09:54 浏览: 81
当然可以,下面是使用 XGBoost 进行分类的代码:
```python
import xgboost as xgb
from sklearn.feature_extraction.text import TfidfVectorizer
# 加载数据
twitter_train_df = csv_loader('sentiment-train.csv')
twitter_test_df = csv_loader('sentiment-test.csv')
# 对文本进行特征提取,并转换为 TF-IDF 矩阵
vectorizer = TfidfVectorizer()
twitter_train_X = vectorizer.fit_transform(twitter_train_df['text'])
twitter_test_X = vectorizer.transform(twitter_test_df['text'])
twitter_train_y = twitter_train_df['sentiment']
twitter_test_y = twitter_test_df['sentiment']
# 构建 XGBoost 模型并训练
dtrain = xgb.DMatrix(twitter_train_X, label=twitter_train_y)
dtest = xgb.DMatrix(twitter_test_X, label=twitter_test_y)
param = {'max_depth': 3, 'eta': 0.1, 'objective': 'multi:softmax', 'num_class': 3}
num_round = 100
bst = xgb.train(param, dtrain, num_round)
# 打印模型在测试集上的准确率
preds = bst.predict(dtest)
accuracy = sum(1 for i in range(len(preds)) if preds[i] == twitter_test_y[i]) / float(len(preds))
print("The accuracy of the trained classifier is {:.2f}%".format(accuracy * 100))
```
需要注意的是,XGBoost 的输入数据需要使用 DMatrix 类型,而且在进行多分类时需要指定 `objective` 参数为 `'multi:softmax'`,并使用 `num_class` 参数指定分类的数量。
阅读全文