Để hoàn thành bài tập này, bạn cần thực hiện các bước sau:
- Tải dữ liệu từ file Book1.xlsx
- Tiền xử lý dữ liệu: chuyển đổi dữ liệu thành tập hợp câu chữ tiếng Việt đã được xử lý
- Vector hóa dữ liệu: chuyển đổi tập hợp câu chữ đã xử lý thành ma trận
- Xây dựng và huấn luyện mô hình phân loại
- Đánh giá mô hình bằng cách sử dụng dữ liệu kiểm tra
- Dự đoán các đánh giá là khen hay chê (positive hoặc negative)
Dưới đây là một đoạn mã mẫu sử dụng Python và thư viện pandas, sklearn, nltk, unidecode và điếu để xử lý các yêu cầu trên. Trước tiên, hãy cài đặt các gói cần thiết bằng cách chạy lệnh sau trong Google Colab:
!pip install pandas sklearn nltk unidecode
!python -m vltk.download('all')
Sau đó, bạn có thể sử dụng mã sau để thực hiện yêu cầu của bạn:
import pandas as pd
import numpy as np
import string
import unidecode
import re
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
from nltk.corpus import stopwords as nltk_stopwords
# Xử lý dữ liệu đầu vào
def pre_process(text):
# Xóa dấu câu và chuyển thành chữ thường
text = text.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation)))
text = unidecode.unidecode(text).lower()
# Loại bỏ stop words
nltk_stopwords.set_lang("vietnamese")
stop_words = set(nltk_stopwords.words())
re_stop_words = re.compile(r"\b(" + "|".join(stop_words) + ")\\W", re.I)
text = re_stop_words.sub(" ", text)
return text
# Tải dữ liệu từ file excel
data = pd.read_excel('Book1.xlsx')
# Tiền xử lý dữ liệu
data['Content'] = data['Content'].apply(pre_process)
X = data['Content']
# Chia tập dữ liệu thành tập huấn luyện và tập kiểm tra
X_train, X_test, y_train, y_test = train_test_split(X, data['id'], test_size=0.2, random_state=42)
# Vector hóa dữ liệu sử dụng Tfidf
vectorizer = TfidfVectorizer()
X_train_vec = vectorizer.fit_transform(X_train)
X_test_vec = vectorizer.transform(X_test)
# Huấn luyện mô hình phân loại Naive Bayes
clf = MultinomialNB()
clf.fit(X_train_vec, y_train)
# Đánh giá mô hình
y_pred = clf.predict(X_test_vec)
print("Độ chính xác: ", accuracy_score(y_test, y_pred))
# Dự đoán các đánh giá là khen hay chê
reviews = list(data['Content'].values)
review_ids = list(data['id'].values)
results = []
for i, review in enumerate(reviews):
review_vec = vectorizer.transform([review])
prediction = clf.predict(review_vec)
if prediction[0] == 1:
sentiment = 'positive'
else:
sentiment = 'negative'
results.append((review_ids[i], sentiment))
# In kết quả
for result in results:
print(f"ID: {result[0]}, Sentiment: {result[1]}")
Mã trên sẽ giúp bạn thực hiện các yêu cầu và in ra các kết quả đánh giá dựa trên dữ liệu đầu vào. Tuy nhiên, để đạt được kết quả tốt nhất, bạn có thể cần phải điều chỉnh một số tham số hoặc thêm bước tiền xử lý dữ liệu.