|
import pickle |
|
import numpy as np |
|
from gensim.models import KeyedVectors |
|
import gradio as gr |
|
|
|
|
|
fasttext_model = KeyedVectors.load_word2vec_format( |
|
'cc.id.300.vec', binary=False |
|
) |
|
|
|
|
|
with open('KNN+GridSearch.pkl', 'rb') as f: |
|
knn_model = pickle.load(f) |
|
|
|
with open('SVM+GridSearch.pkl', 'rb') as f: |
|
svm_model = pickle.load(f) |
|
|
|
|
|
def get_fasttext_vector(text): |
|
|
|
words = text.split() |
|
|
|
|
|
word_vectors = [fasttext_model[word] for word in words if word in fasttext_model] |
|
|
|
|
|
if len(word_vectors) > 0: |
|
return np.mean(word_vectors, axis=0) |
|
else: |
|
|
|
return np.zeros(fasttext_model.vector_size) |
|
|
|
|
|
def predict_sentiment_knn(text): |
|
vector = get_fasttext_vector(text) |
|
sentiment = knn_model.predict([vector]) |
|
return sentiment[0][0] |
|
|
|
|
|
def predict_sentiment_svm(text): |
|
vector = get_fasttext_vector(text) |
|
sentiment = svm_model.predict([vector]) |
|
return sentiment[0] |
|
|
|
|
|
def predict_sentiment(text, model_type='KNN'): |
|
if model_type == 'KNN': |
|
return predict_sentiment_knn(text) |
|
else: |
|
return predict_sentiment_svm(text) |
|
|
|
|
|
gr.Interface( |
|
fn=predict_sentiment, |
|
inputs=[ |
|
gr.inputs.Textbox(label="Masukkan Teks untuk Analisis Sentimen"), |
|
gr.inputs.Radio(['KNN', 'SVM'], label="Pilih Model") |
|
], |
|
outputs="text" |
|
).launch() |
|
|