Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions svm_sentiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
svm_sentiment.py
SVM-based Sentiment Analysis Example for TextBlob contribution.

-----------------
Example sentiment classifier using Support Vector Machines (SVM)
"""

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.svm import LinearSVC


class SVMSentimentClassifier:
def __init__(self):
self.model = make_pipeline(TfidfVectorizer(), LinearSVC())

def train(self, texts, labels):
"""Train the classifier with labeled tetx data"""
self.model.fit(texts, labels)

def predict(self, text):
return self.model.predict([text])[0]


if __name__ == "__main__":
texts = [
"I love this movie!",
"That was terrible.",
"It's okay, not bad",
"Absolutely amazing",
"Worst thing ever.",
"Fine but forgettable.",
]
labels = ["positive", "negative", "neutral", "positive", "negative", "neutral"]

clf = SVMSentimentClassifier()
clf.train(texts, labels)

test = ["This was awesome!", "I didn't like it.", "It's average."]
for t in test:
print(t, "->", clf.predict(t))
45 changes: 45 additions & 0 deletions test_svm_sentiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
test_svm_sentiment.py
unit tests for SVMSentimentClassifier.
"""

import pytest
from svm_sentiment import SVMSentimentClassifier


@pytest.fixture
def trained_classifier():
texts = [
"I love this movie!",
"That was terrible.",
"It's okay, not bad",
"Absolutely amazing",
"Worst thing ever.",
"Fine but forgettable.",
]
labels = ["positive", "negative", "neutral", "positive", "negative", "neutral"]

clf = SVMSentimentClassifier()
clf.train(texts, labels)
return clf


def test_positive_sentiment(trained_classifier):
result = trained_classifier.predict("This is fantastic!")
assert result in ["positive", "negative", "neutral"]


def test_negative_sentiment(trained_classifier):
result = trained_classifier.predict("I really hated it")
assert result in ["positive", "negative", "neutral"]


def test_neutral_sentiment(trained_classifier):
result = trained_classifier.predict("It was fine, nothing special.")
assert result in ["positive", "negative", "neutral"]


def test_model_training_required():
clf = SVMSentimentClassifier()
with pytest.raises(Exception):
clf.predict("I love it!")