mobrown commited on
Commit
dcb533f
1 Parent(s): 7702cd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -111
app.py CHANGED
@@ -1,114 +1,98 @@
1
- import numpy as np
2
- from sklearn.decomposition import PCA
3
- import gensim.downloader as api
4
  import gradio as gr
5
- import plotly.graph_objects as go
6
-
7
- # Load the Word2Vec model
8
- model = api.load("word2vec-google-news-300")
9
-
10
-
11
- def gensim_analogy(model, word1, word2, word3):
12
- try:
13
- result = model.most_similar(positive=[word2, word3], negative=[word1], topn=1)
14
- return result[0][0] # Return the word
15
- except KeyError as e:
16
- return str(e)
17
-
18
-
19
- def plot_words_plotly(model, words):
20
- vectors = np.array([model[word] for word in words if word in model.key_to_index])
21
-
22
- # Reduce dimensions to 2D for plotting
23
- pca = PCA(n_components=2)
24
- vectors_2d = pca.fit_transform(vectors)
25
-
26
- # Create a scatter plot
27
- fig = go.Figure()
28
-
29
- # Add scatter points for each word vector
30
- for word, vec in zip(words, vectors_2d):
31
- fig.add_trace(go.Scatter(x=[vec[0]], y=[vec[1]],
32
- text=[word], mode='markers+text',
33
- textposition="bottom center",
34
- name=word))
35
-
36
- fig.update_layout(title="Visualization of Word Vectors",
37
- xaxis_title="PCA 1",
38
- yaxis_title="PCA 2",
39
- showlegend=True,
40
- width=600, # Adjust width as needed
41
- height=400) # Adjust height as needed
42
-
43
- return fig
44
-
45
-
46
- def gradio_interface(choice, custom_input):
47
- if choice == "Custom":
48
- if not custom_input or len(custom_input.split(", ")) != 3:
49
- return "Invalid input. Please enter exactly three words, separated by commas.", None, {
50
- "error": "Invalid input"}
51
- words = custom_input.split(", ")
52
- else:
53
- if not choice:
54
- return "Invalid input. Please select or enter words.", None, {
55
- "error": "Invalid input"}
56
- words = choice.split(", ")
57
-
58
- word1, word2, word3 = words
59
- word4 = gensim_analogy(model, word1, word2, word3)
60
- plot_fig = plot_words_plotly(model, [word1, word2, word3, word4])
61
-
62
- if word4 in model.key_to_index:
63
- vector = model[word4]
64
- vector_display = f"{word4}: {np.round(vector, 2).tolist()}"
65
- else:
66
- vector_display = "Vector not available for the resulting word"
67
-
68
- return word4, plot_fig, vector_display
69
-
70
-
71
- choices = [
72
- "man, king, woman",
73
- "Paris, France, London",
74
- "strong, stronger, weak",
75
- "pork, pig, beef",
76
- "Custom"
77
  ]
78
 
79
-
80
- def clear_inputs():
81
- return "", "", "", "", None
82
-
83
-
84
- # Define the layout using Rows and Columns
85
- with gr.Blocks() as iface:
86
- with gr.Row():
87
- with gr.Column():
88
- gr.Markdown("# Word Analogy and Vector Visualization")
89
- gr.Markdown(
90
- "Select a predefined triplet of words or choose 'Custom' and enter your own (comma-separated) to find a fourth word by analogy, and see their vectors plotted with Plotly.")
91
-
92
- radio = gr.Radio(choices=choices, label="Choose predefined words or enter custom words")
93
-
94
- custom_words = gr.Textbox(
95
- label="Custom words (comma-separated, required for custom choice; use only if 'Custom' is selected)",
96
- placeholder="Enter 3 words separated by commas")
97
-
98
- with gr.Row():
99
- clear_btn = gr.Button("Clear")
100
- submit_btn = gr.Button("Submit")
101
-
102
- output_word = gr.Textbox(label="Output Word")
103
-
104
- word_plot = gr.Plot(label="Word Vectors Visualization")
105
-
106
- with gr.Row():
107
- word_vectorization = gr.Textbox(label="Vectorization of the Output Word", lines=4, max_lines=4)
108
-
109
- clear_btn.click(fn=clear_inputs, inputs=None,
110
- outputs=[radio, custom_words, output_word, word_vectorization, word_plot])
111
- submit_btn.click(fn=gradio_interface, inputs=[radio, custom_words],
112
- outputs=[output_word, word_plot, word_vectorization])
113
-
114
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from sklearn.feature_extraction.text import TfidfVectorizer
4
+ from sklearn.naive_bayes import MultinomialNB
5
+ from sklearn.svm import SVC
6
+ from sklearn.ensemble import RandomForestClassifier
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn import metrics
10
+ import pandas as pd
11
+
12
+ # Load the provided dataset
13
+ file_path = 'data.csv'
14
+ df = pd.read_csv(file_path)
15
+
16
+ # Split data into training and test sets
17
+ X_train, X_test, y_train, y_test = train_test_split(df['Sentence'], df['Sentiment'], test_size=0.2, random_state=42)
18
+
19
+ # Define models
20
+ nb_model = make_pipeline(TfidfVectorizer(), MultinomialNB())
21
+ svm_model = make_pipeline(TfidfVectorizer(), SVC(probability=True))
22
+ rf_model = make_pipeline(TfidfVectorizer(), RandomForestClassifier())
23
+
24
+ # Train models
25
+ nb_model.fit(X_train, y_train)
26
+ svm_model.fit(X_train, y_train)
27
+ rf_model.fit(X_train, y_train)
28
+
29
+ # Define sentences to choose from
30
+ sentences = [
31
+ "The announced restructuring will significantly decrease the company's indebtedness.",
32
+ "UPM-Kymmene upgraded to `in-line' from `underperform' by Goldman Sachs.",
33
+ "$AAPL shares are breaking out of the recent resistance level.",
34
+ "Profitability (in EBIT %) was 13.6%, compared to 14.3% in Q2 2009.",
35
+ "The Finnish bank has issued a profit warning.",
36
+ "TeliaSonera's underlying results however included 457 mln SKr in positive one-offs, hence the adjusted underlying EBITDA actually amounts to 7.309 bln SKr, clearly below expectations, analysts said."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  ]
38
 
39
+ # Function to map BERT labels
40
+ def map_bert_label(label):
41
+ if label in ["1 star", "2 stars"]:
42
+ return "negative"
43
+ elif label == "3 stars":
44
+ return "neutral"
45
+ elif label in ["4 stars", "5 stars"]:
46
+ return "positive"
47
+
48
+
49
+ # Function to map RoBERTa labels
50
+ def map_roberta_label(label):
51
+ label_mapping = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"}
52
+ return label_mapping[label]
53
+
54
+
55
+ # Function to analyze sentiment
56
+ def analyze_sentiment(sentence):
57
+ # Define model paths
58
+ model_paths = {
59
+ "FinBert": "ProsusAI/finbert",
60
+ "BERT": "nlptown/bert-base-multilingual-uncased-sentiment",
61
+ "RoBERTa": "cardiffnlp/twitter-roberta-base-sentiment"
62
+ }
63
+
64
+ # Analyze sentiment using transformers models
65
+ results = {}
66
+ for model_name, model_path in model_paths.items():
67
+ sentiment_analyzer = pipeline("sentiment-analysis", model=model_path)
68
+ result = sentiment_analyzer(sentence[:512])[0] # Analyze first 512 characters for brevity
69
+
70
+ if model_name == "BERT":
71
+ result['label'] = map_bert_label(result['label'])
72
+ elif model_name == "RoBERTa":
73
+ result['label'] = map_roberta_label(result['label'])
74
+
75
+ results[model_name] = result
76
+
77
+ # Analyze sentiment using sklearn models
78
+ results["Naive Bayes"] = {"label": nb_model.predict([sentence])[0],
79
+ "score": nb_model.predict_proba([sentence]).max()}
80
+ results["SVM"] = {"label": svm_model.predict([sentence])[0], "score": svm_model.predict_proba([sentence]).max()}
81
+ results["Random Forest"] = {"label": rf_model.predict([sentence])[0],
82
+ "score": rf_model.predict_proba([sentence]).max()}
83
+
84
+ return sentence, results
85
+
86
+
87
+ # Create Gradio interface
88
+ dropdown = gr.Dropdown(choices=sentences, label="Select Sentence")
89
+ text_output = gr.Textbox(label="Selected Sentence", lines=2)
90
+ sentiment_output = gr.JSON(label="Sentiment Scores")
91
+
92
+ gr.Interface(
93
+ fn=analyze_sentiment,
94
+ inputs=[dropdown],
95
+ outputs=[text_output, sentiment_output],
96
+ title="Compare Sentiment Analysis Across Models",
97
+ description="Select a sentence to see sentiment analysis results from multiple models."
98
+ ).launch(share=True)