great-ai/examples/simple/deploy.ipynb

172 lines
8.8 KiB
Text

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Train a domain classifier on the [semantic scholar dataset](https://api.semanticscholar.org/corpus)\n",
"\n",
"## Part 3: Create production inference function\n",
"\n",
"In the [previous notebook](train.ipynb), we trained our AI model. Now, it's time to create **G**eneral **R**obust **E**nd-to-end **A**utomated **T**rustworthy deployment from it using the `GreatAI` Python package."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from typing import List\n",
"import re\n",
"from great_ai import ClassificationOutput, GreatAI, use_model\n",
"from sklearn.pipeline import Pipeline\n",
"from great_ai.utilities.clean import clean"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[38;5;226m2022-05-28 18:17:13,344 | WARNING | Environment variable ENVIRONMENT is not set, defaulting to development mode ‼️\u001b[0m\n",
"\u001b[38;5;39m2022-05-28 18:17:13,346 | INFO | Options: configured ✅\u001b[0m\n",
"\u001b[38;5;39m2022-05-28 18:17:13,694 | INFO | Latest version of small-domain-prediction is 10 (from versions: 9, 10)\u001b[0m\n",
"\u001b[38;5;39m2022-05-28 18:17:13,694 | INFO | File small-domain-prediction-10 found in cache\u001b[0m\n"
]
}
],
"source": [
"@GreatAI.deploy\n",
"@use_model(\"small-domain-prediction\", version=\"latest\")\n",
"def predict_domain(\n",
" text: str, model: Pipeline, target_confidence: int = 50\n",
") -> List[ClassificationOutput]:\n",
" \"\"\"\n",
" Predict the scientific domain of the input text.\n",
" Return labels until their sum likelihood is larger than target_confidence.\n",
" \"\"\"\n",
" assert 0 <= target_confidence <= 100, \"invalid argument\"\n",
"\n",
" preprocessed = re.sub(r\"[^a-zA-Z\\s]\", \"\", clean(text, convert_to_ascii=True))\n",
" features = model.named_steps[\"vectorizer\"].transform([preprocessed])\n",
" prediction = model.named_steps[\"classifier\"].predict_proba(features)[0]\n",
"\n",
" best_classes = sorted(enumerate(prediction), key=lambda v: v[1], reverse=True)\n",
"\n",
" results: List[ClassificationOutput] = []\n",
" for class_index, probability in best_classes:\n",
" results.append(\n",
" ClassificationOutput(\n",
" label=model.named_steps[\"classifier\"].classes_[class_index],\n",
" confidence=round(probability * 100),\n",
" explanation=[\n",
" word\n",
" for _, word in sorted(\n",
" (\n",
" (weight, word)\n",
" for weight, word, count in zip(\n",
" model.named_steps[\"classifier\"].feature_log_prob_[\n",
" class_index\n",
" ],\n",
" model.named_steps[\"vectorizer\"].get_feature_names_out(),\n",
" features.A[0],\n",
" )\n",
" if count > 0\n",
" ),\n",
" reverse=True,\n",
" )\n",
" ][:5],\n",
" )\n",
" )\n",
"\n",
" if sum(r.confidence for r in results) >= target_confidence:\n",
" break\n",
"\n",
" return results"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'created': '2022-05-28T16:17:14.581693',\n",
" 'exception': None,\n",
" 'execution_time_ms': 93.638,\n",
" 'feedback': None,\n",
" 'logged_values': {'arg:predict_domain:target_confidence': 50,\n",
" 'arg:predict_domain:text': '\\n'\n",
" ' State-of-the-art methods for zero-shot visual recognition formulate '\n",
" 'learning as a joint embedding problem of images and side information. '\n",
" 'In these formulations the current best complement to visual features '\n",
" 'are attributes: manually encoded vectors describing shared '\n",
" 'characteristics among categories. Despite good performance, attributes '\n",
" 'have limitations: (1) finer-grained recognition requires commensurately '\n",
" 'more, and (2) attributes do not provide a natural language interface. '\n",
" 'We propose to overcome these limitations by training neural language '\n",
" 'models from scratch; i.e. without pre-training and only consuming words '\n",
" 'and characters. Our proposed models train end-to-end to align with the '\n",
" 'fine-grained and category-specific content of images. Natural language '\n",
" 'provides a flexible and compact way of encoding only the salient visual '\n",
" 'aspects for distinguishing categories. By training on raw text, our '\n",
" 'model can do inference on raw text as well, providing humans a familiar '\n",
" 'mode both for annotation and retrieval. Our model achieves strong '\n",
" 'performance on zero-shot text-based image retrieval and significantly '\n",
" 'outperforms the attribute-based state-of-the-art for zero-shot '\n",
" 'classification on the CaltechUCSD Birds 200-2011 dataset. ',\n",
" 'arg:predict_domain:text:length': 1236},\n",
" 'models': [{'key': 'small-domain-prediction', 'version': 10}],\n",
" 'output': [{'confidence': 99.0,\n",
" 'explanation': ['information', 'model', 'learning', 'proposed', 'image'],\n",
" 'label': 'Computer Science'}],\n",
" 'trace_id': 'd35fcb96-0a95-45f8-93e4-8967160b17dd'}\n"
]
}
],
"source": [
"# result = predict_domain(\n",
"# \"\"\"\n",
"# State-of-the-art methods for zero-shot visual recognition formulate learning as a joint embedding problem of images and side information. In these formulations the current best complement to visual features are attributes: manually encoded vectors describing shared characteristics among categories. Despite good performance, attributes have limitations: (1) finer-grained recognition requires commensurately more, and (2) attributes do not provide a natural language interface. We propose to overcome these limitations by training neural language models from scratch; i.e. without pre-training and only consuming words and characters. Our proposed models train end-to-end to align with the fine-grained and category-specific content of images. Natural language provides a flexible and compact way of encoding only the salient visual aspects for distinguishing categories. By training on raw text, our model can do inference on raw text as well, providing humans a familiar mode both for annotation and retrieval. Our model achieves strong performance on zero-shot text-based image retrieval and significantly outperforms the attribute-based state-of-the-art for zero-shot classification on the CaltechUCSD Birds 200-2011 dataset. \"\"\"\n",
"# )\n",
"\n",
"# from pprint import pprint\n",
"\n",
"# # pprint(result.dict(), width=120)"
]
}
],
"metadata": {
"interpreter": {
"hash": "9583b8c15346c7ad861da481b60c8e8605a71a48eda767f1640baa8f25efebcb"
},
"kernelspec": {
"display_name": "Python 3.9.2 ('.venv': venv)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}