ktr008 commited on
Commit
b807f44
Β·
verified Β·
1 Parent(s): d7e26f0

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +206 -1
README.md CHANGED
@@ -10,4 +10,209 @@ pinned: false
10
  short_description: TweetSentimnet
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  short_description: TweetSentimnet
11
  ---
12
 
13
+ Here's a **complete documentation** for deploying your **fine-tuned sentiment analysis model** using **Hugging Face Spaces and Gradio**.
14
+
15
+ ---
16
+
17
+ # **Fine-Tuned Sentiment Analysis Deployment Guide**
18
+
19
+ This guide explains how to **fine-tune, save, upload, and deploy** a sentiment analysis model using **Hugging Face Transformers, Gradio, and Hugging Face Spaces**.
20
+
21
+ ---
22
+
23
+ ## **1. Prerequisites**
24
+ Before proceeding, ensure you have the following installed:
25
+
26
+ ### **Install Required Libraries**
27
+ ```bash
28
+ pip install gradio transformers torch scipy numpy
29
+ ```
30
+
31
+ If you're using **TensorFlow-based models**, also install:
32
+ ```bash
33
+ pip install tensorflow
34
+ ```
35
+
36
+ ### **Hugging Face Authentication**
37
+ Login to Hugging Face CLI:
38
+ ```bash
39
+ huggingface-cli login
40
+ ```
41
+ (You'll need an **access token** from [Hugging Face](https://huggingface.co/settings/tokens).)
42
+
43
+ ---
44
+
45
+ ## **2. Fine-Tune Your Sentiment Analysis Model**
46
+ ### **Training a Custom Sentiment Model**
47
+ If you haven't already fine-tuned a model, you can do so using `Trainer` from Hugging Face:
48
+
49
+ ```python
50
+ from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments, AutoTokenizer
51
+ from datasets import load_dataset
52
+
53
+ # Load dataset
54
+ dataset = load_dataset("imdb") # Example dataset
55
+
56
+ # Load tokenizer and model
57
+ model_name = "cardiffnlp/twitter-roberta-base-sentiment-latest"
58
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
59
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=3)
60
+
61
+ # Tokenize dataset
62
+ def preprocess(examples):
63
+ return tokenizer(examples["text"], truncation=True, padding="max_length")
64
+
65
+ tokenized_datasets = dataset.map(preprocess, batched=True)
66
+
67
+ # Training Arguments
68
+ training_args = TrainingArguments(
69
+ output_dir="./fine_tuned_sentiment_model",
70
+ evaluation_strategy="epoch",
71
+ save_strategy="epoch",
72
+ per_device_train_batch_size=8,
73
+ per_device_eval_batch_size=8,
74
+ num_train_epochs=3,
75
+ weight_decay=0.01,
76
+ logging_dir="./logs",
77
+ )
78
+
79
+ # Trainer
80
+ trainer = Trainer(
81
+ model=model,
82
+ args=training_args,
83
+ train_dataset=tokenized_datasets["train"],
84
+ eval_dataset=tokenized_datasets["test"],
85
+ )
86
+
87
+ # Train Model
88
+ trainer.train()
89
+
90
+ # Save Model
91
+ model.save_pretrained("./fine_tuned_sentiment_model")
92
+ tokenizer.save_pretrained("./fine_tuned_sentiment_model")
93
+ ```
94
+
95
+ ---
96
+
97
+ ## **3. Upload Model to Hugging Face Hub**
98
+ Once you've fine-tuned your model, upload it to **Hugging Face Model Hub**:
99
+
100
+ ### **1. Install `huggingface_hub`**
101
+ ```bash
102
+ pip install huggingface_hub
103
+ ```
104
+
105
+ ### **2. Push Model to Hugging Face**
106
+ ```python
107
+ from huggingface_hub import notebook_login
108
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
109
+
110
+ notebook_login() # Authenticate
111
+
112
+ # Define model name
113
+ repo_name = "your-username/sentiment-analysis-model"
114
+
115
+ # Load fine-tuned model
116
+ model = AutoModelForSequenceClassification.from_pretrained("./fine_tuned_sentiment_model")
117
+ tokenizer = AutoTokenizer.from_pretrained("./fine_tuned_sentiment_model")
118
+
119
+ # Push model to Hugging Face Hub
120
+ model.push_to_hub(repo_name)
121
+ tokenizer.push_to_hub(repo_name)
122
+ ```
123
+
124
+ Your fine-tuned model is now available at **https://huggingface.co/your-username/sentiment-analysis-model**.
125
+
126
+ ---
127
+
128
+ ## **4. Deploy Sentiment Model Using Gradio**
129
+ To create a **Gradio-based web interface**, follow these steps:
130
+
131
+ ### **1. Create `app.py`**
132
+ Save the following script as `app.py`:
133
+
134
+ ```python
135
+ import gradio as gr
136
+ import numpy as np
137
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
138
+ from scipy.special import softmax
139
+
140
+ # Load fine-tuned model from Hugging Face Hub
141
+ MODEL_NAME = "your-username/sentiment-analysis-model" # Replace with your model repo
142
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
143
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
144
+ config = AutoConfig.from_pretrained(MODEL_NAME)
145
+
146
+ # Preprocess function
147
+ def preprocess(text):
148
+ new_text = []
149
+ for t in text.split(" "):
150
+ t = '@user' if t.startswith('@') and len(t) > 1 else t
151
+ t = 'http' if t.startswith('http') else t
152
+ new_text.append(t)
153
+ return " ".join(new_text)
154
+
155
+ # Sentiment Prediction Function
156
+ def predict_sentiment(text):
157
+ text = preprocess(text)
158
+ encoded_input = tokenizer(text, return_tensors='pt')
159
+ output = model(**encoded_input)
160
+ scores = output[0][0].detach().numpy()
161
+ scores = softmax(scores)
162
+
163
+ # Get sentiment labels and scores
164
+ ranking = np.argsort(scores)[::-1]
165
+ result = {config.id2label[ranking[i]]: round(float(scores[ranking[i]]) * 100, 2) for i in range(scores.shape[0])}
166
+ return result
167
+
168
+ # Gradio Interface
169
+ interface = gr.Interface(
170
+ fn=predict_sentiment,
171
+ inputs=gr.Textbox(lines=3, placeholder="Enter text..."),
172
+ outputs=gr.Label(),
173
+ title="Fine-Tuned Sentiment Analysis",
174
+ description="Enter a sentence to analyze its sentiment (Positive, Neutral, Negative).",
175
+ )
176
+
177
+ # Launch the app
178
+ interface.launch()
179
+ ```
180
+
181
+ ---
182
+
183
+ ## **5. Upload to Hugging Face Spaces**
184
+ ### **1. Create a Hugging Face Space**
185
+ - Go to [Hugging Face Spaces](https://huggingface.co/spaces).
186
+ - Click **Create new Space**.
187
+ - Choose **Gradio** as the SDK.
188
+ - Set the repository name (e.g., `sentiment-analysis-app`).
189
+ - Click **Create Space**.
190
+
191
+ ### **2. Upload Files**
192
+ - Upload `app.py` in the Space repository.
193
+ - Create and upload a `requirements.txt` file with:
194
+ ```
195
+ gradio
196
+ transformers
197
+ torch
198
+ scipy
199
+ numpy
200
+ ```
201
+
202
+ ### **3. Deploy the Model**
203
+ Once the files are uploaded, Hugging Face will **automatically install dependencies** and **launch the app**. You can access it via the **public URL** provided by Hugging Face.
204
+
205
+ ---
206
+
207
+ ## **6. Testing & Sharing**
208
+ Once deployed, test the model by entering different texts and see the predicted sentiment. Share the **public Hugging Face Space link** with others to let them use it.
209
+
210
+ ---
211
+
212
+ ## **7. Summary**
213
+ ### βœ… **Fine-tune a sentiment analysis model**
214
+ ### βœ… **Upload it to Hugging Face Model Hub**
215
+ ### βœ… **Deploy it using Gradio & Hugging Face Spaces**
216
+ ### βœ… **Make it publicly accessible for users**
217
+
218
+ πŸš€ **Your fine-tuned sentiment analysis model is now LIVE!** πŸŽ‰