Jekyll2000 commited on
Commit
2f98bd3
1 Parent(s): 51076df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ from tensorflow.keras import layers, models
3
+ from tensorflow.keras.preprocessing.text import Tokenizer
4
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
5
+ import gradio as gr
6
+
7
+ # Load the IMDb dataset
8
+ imdb = tf.keras.datasets.imdb
9
+ vocab_size = 10000
10
+ maxlen = 100
11
+ (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=vocab_size)
12
+ X_train = pad_sequences(X_train, maxlen=maxlen)
13
+ X_test = pad_sequences(X_test, maxlen=maxlen)
14
+
15
+ # Define the model
16
+ model = models.Sequential([
17
+ layers.Embedding(vocab_size, 16, input_length=maxlen),
18
+ layers.GlobalAveragePooling1D(),
19
+ layers.Dense(16, activation='relu'),
20
+ layers.Dense(1, activation='sigmoid')
21
+ ])
22
+
23
+ model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
24
+ model.fit(X_train, y_train, epochs=10, batch_size=512, validation_data=(X_test, y_test), verbose=1)
25
+
26
+ # Save the model
27
+ model.save("sentiment_analysis_model.h5")
28
+
29
+ # Function to predict sentiment
30
+ def predict_sentiment(text):
31
+ tokenizer = Tokenizer(num_words=vocab_size)
32
+ tokenizer.fit_on_texts([text])
33
+ sequence = tokenizer.texts_to_sequences([text])
34
+ padded_sequence = pad_sequences(sequence, maxlen=maxlen)
35
+
36
+ prediction = model.predict(padded_sequence)[0][0]
37
+ sentiment = "Positive" if prediction >= 0.5 else "Negative"
38
+ confidence = round(prediction, 4)
39
+
40
+ return sentiment, confidence
41
+
42
+ # Gradio Interface
43
+ def gradio_predict(text):
44
+ sentiment, confidence = predict_sentiment(text)
45
+ return f"Sentiment: {sentiment}, Confidence: {confidence:.4f}"
46
+
47
+ # Create Gradio Interface
48
+ interface = gr.Interface(fn=gradio_predict,
49
+ inputs=gr.Textbox(lines=2, placeholder="Enter your text here..."),
50
+ outputs="text",
51
+ title="Sentiment Analysis",
52
+ description="Enter a movie review or any text to analyze its sentiment.")
53
+
54
+ # Launch the Gradio Interface
55
+ interface.launch()