-
Notifications
You must be signed in to change notification settings - Fork 268
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
211 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"%reload_ext autoreload\n", | ||
"%autoreload 2\n", | ||
"%matplotlib inline\n", | ||
"import os\n", | ||
"os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\";\n", | ||
"os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"; " | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"from ktrain.text.sentiment import SentimentAnalyzer" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"classifier = SentimentAnalyzer()" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"texts = [\"The lower pollen count has provided some relief from my allergies.\", \n", | ||
" \"It looks like there will be cost overruns.\",\n", | ||
" \"I will be at a doctor's appointment at 3:30pm.\",\n", | ||
" \"Tesla stock is falling.\"]" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"data": { | ||
"text/plain": [ | ||
"[{'POSITIVE': 0.8364812731742859},\n", | ||
" {'NEGATIVE': 0.7623286247253418},\n", | ||
" {'NEUTRAL': 0.9303346276283264},\n", | ||
" {'NEGATIVE': 0.7317317724227905}]" | ||
] | ||
}, | ||
"execution_count": null, | ||
"metadata": {}, | ||
"output_type": "execute_result" | ||
} | ||
], | ||
"source": [ | ||
"classifier.predict(texts)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"data": { | ||
"text/plain": [ | ||
"{'POSITIVE': 0.9378765821456909,\n", | ||
" 'NEUTRAL': 0.06050467491149902,\n", | ||
" 'NEGATIVE': 0.0016188238514587283}" | ||
] | ||
}, | ||
"execution_count": null, | ||
"metadata": {}, | ||
"output_type": "execute_result" | ||
} | ||
], | ||
"source": [ | ||
"classifier.predict(\"I got a promotion at work today.\", return_all_scores=True) " | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "python3", | ||
"language": "python", | ||
"name": "python3" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .core import SentimentAnalyzer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
from typing import Union | ||
from transformers import pipeline | ||
|
||
from ... import utils as U | ||
from ...torch_base import TorchBase | ||
|
||
|
||
class SentimentAnalyzer(TorchBase): | ||
""" | ||
interface to Sentiment Analyzer | ||
""" | ||
|
||
def __init__(self, device=None, **kwargs): | ||
""" | ||
``` | ||
ImageCaptioner constructor | ||
Args: | ||
device(str): device to use (e.g., 'cuda', 'cpu') | ||
``` | ||
""" | ||
|
||
super().__init__( | ||
device=device, quantize=False, min_transformers_version="4.12.3" | ||
) | ||
self.pipeline = pipeline( | ||
"text-classification", | ||
model="cardiffnlp/twitter-roberta-base-sentiment", | ||
device=self.device_to_id(), | ||
**kwargs | ||
) | ||
self.mapping = { | ||
"LABEL_0": "NEGATIVE", | ||
"LABEL_1": "NEUTRAL", | ||
"LABEL_2": "POSITIVE", | ||
} | ||
|
||
def predict( | ||
self, | ||
texts: Union[str, list], | ||
return_all_scores=False, | ||
batch_size=U.DEFAULT_BS, | ||
**kwargs | ||
): | ||
""" | ||
``` | ||
Performs sentiment analysis | ||
This method accepts a list of texts and predicts their sentiment as either 'NEGATIVE', 'NEUTRAL', 'POSITIVE'. | ||
Args: | ||
texts: str|list | ||
return_all_scores(bool): If True, return all labels/scores | ||
batch_size: size of batches sent to model | ||
Returns: | ||
A dictionary of labels and scores | ||
``` | ||
""" | ||
str_input = isinstance(texts, str) | ||
if str_input: | ||
texts = [texts] | ||
chunks = U.batchify(texts, batch_size) | ||
results = [] | ||
for chunk in chunks: | ||
preds = self.pipeline( | ||
chunk, top_k=len(self.mapping) if return_all_scores else 1, **kwargs | ||
) | ||
results.extend(preds) | ||
results = [self._flatten_prediction(pred) for pred in results] | ||
return results[0] if str_input else results | ||
|
||
def _flatten_prediction(self, prediction: list): | ||
""" | ||
``` | ||
flatten prediction to the form {'label':score} | ||
``` | ||
""" | ||
return_dict = {} | ||
for d in prediction: | ||
return_dict[self.mapping[d["label"]]] = d["score"] | ||
return return_dict |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
__all__ = ["__version__"] | ||
__version__ = "0.35.2" | ||
__version__ = "0.36.dev" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters