yxmauw commited on
Commit
4f78275
1 Parent(s): 52f9d46
Files changed (10) hide show
  1. .gitattributes +1 -0
  2. ML_model.py +76 -0
  3. app.py +71 -0
  4. final_model.sav +3 -0
  5. highlight_text.css +23 -0
  6. load_css.py +8 -0
  7. model_methods.py +45 -0
  8. requirements.txt +6 -0
  9. subreddit_icon.png +0 -0
  10. tts.csv +0 -0
.gitattributes CHANGED
@@ -29,3 +29,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
29
  *.zip filter=lfs diff=lfs merge=lfs -text
30
  *.zst filter=lfs diff=lfs merge=lfs -text
31
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
29
  *.zip filter=lfs diff=lfs merge=lfs -text
30
  *.zst filter=lfs diff=lfs merge=lfs -text
31
  *tfevents* filter=lfs diff=lfs merge=lfs -text
32
+ *.sav filter=lfs diff=lfs merge=lfs -text
ML_model.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from nltk.tokenize import RegexpTokenizer
4
+ from nltk.stem import WordNetLemmatizer
5
+ from nltk.corpus import stopwords
6
+ from sklearn.feature_extraction.text import CountVectorizer
7
+ import re
8
+
9
+ from sklearn.model_selection import train_test_split
10
+ from sklearn.model_selection import GridSearchCV
11
+ from sklearn.pipeline import Pipeline
12
+ from sklearn.naive_bayes import MultinomialNB
13
+
14
+ import pickle
15
+
16
+ # import dataset 'full_post' that has been lemmatized
17
+ url = 'https://raw.githubusercontent.com/yxmauw/General_Assembly_Pub/main/project_3/cloud_app/tts.csv'
18
+ df = pd.read_csv(url, header=0)
19
+
20
+ # train-test-split
21
+ X = df['full_post'] # pd.series because dataframe format not friendly for word vectorization
22
+ y = df['subreddit']
23
+
24
+ # make sure target variable has equal representation on both train and test sets
25
+ X_train, X_test, y_train, y_test = train_test_split(X, y,
26
+ test_size=.2,
27
+ stratify=y,
28
+ random_state=42)
29
+
30
+ # lemmatizing
31
+ def lemmatize_join(text):
32
+ tokenizer = RegexpTokenizer('[a-z]+', gaps=False) # instantiate tokenizer
33
+ lemmer = WordNetLemmatizer() # instantiate lemmatizer
34
+ return ' '.join([lemmer.lemmatize(w) for w in tokenizer.tokenize(text.lower())])
35
+ # lowercase, join back together with spaces so that word vectorizers can still operate
36
+ # on cell contents as strings
37
+
38
+ Z_train = X_train.apply(lemmatize_join)
39
+
40
+ # model instantiation
41
+ pipe_cvec_nb = Pipeline([
42
+ ('cvec', CountVectorizer()),
43
+ ('nb', MultinomialNB())
44
+ ])
45
+
46
+ # word vectorizor parameters
47
+ features = [1000]
48
+ min_df = [3]
49
+ max_df = [.6]
50
+ ngrams = [(1,2)]
51
+ stop_words = ['english']
52
+ accent = ['unicode']
53
+
54
+ # naive bayes classifier parameters
55
+ alphas = [.5]
56
+
57
+ cvec_nb_params = [{'cvec__max_features': features,
58
+ 'cvec__min_df': min_df,
59
+ 'cvec__max_df': max_df,
60
+ 'cvec__ngram_range': ngrams,
61
+ 'cvec__lowercase': [False],
62
+ 'cvec__stop_words': stop_words,
63
+ 'cvec__strip_accents': accent,
64
+ 'nb__alpha': alphas
65
+ }]
66
+
67
+ cvec_nb_gs = GridSearchCV(pipe_cvec_nb,
68
+ cvec_nb_params,
69
+ scoring='accuracy',
70
+ cv=5,
71
+ verbose=1,
72
+ n_jobs=-2)
73
+
74
+ cvec_nb_gs.fit(Z_train, y_train)
75
+
76
+ pickle.dump(cvec_nb_gs, open('final_model.sav', 'wb'))
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import pandas as pd
4
+ import numpy as np
5
+ from model_methods import predict
6
+ import base64 # for title image
7
+ from load_css import local_css # for highlighting text
8
+
9
+ @st.cache # cached so that latency for subsequent runs are shorter
10
+ def import_nltk():
11
+ import nltk
12
+ nltk.download('wordnet')
13
+ nltk.download('omw-1.4')
14
+
15
+ # configuration of the page
16
+ st.set_page_config(
17
+ layout='centered',
18
+ page_icon=Image.open('project_3/cloud_app/subreddit_icon.png'),
19
+ page_title='Marvel vs. DC comics',
20
+ initial_sidebar_state='auto'
21
+ )
22
+
23
+ # embed source link in title image using base64 module
24
+ # reference: https://discuss.streamlit.io/t/how-to-show-local-gif-image/3408/4
25
+ # reference: https://discuss.streamlit.io/t/local-image-button/5409/4
26
+ im = open("project_3/cloud_app/subreddit_icon.png", "rb")
27
+ contents = im.read()
28
+ im_base64 = base64.b64encode(contents).decode("utf-8")
29
+ im.close()
30
+ html = f'''<a href='https://www.reddit.com/'>
31
+ <img src='data:image/png;base64,{im_base64}' width='100'>
32
+ </a><figcaption>Credit: reddit.com</figcaption>'''
33
+ st.markdown(html, unsafe_allow_html=True)
34
+
35
+ st.title('Subreddit Post classifier')
36
+ local_css("project_3/cloud_app/highlight_text.css")
37
+ text = '''The algorithm driving this app is built using subreddit posts published
38
+ between April and July 2022. It is only able to classify between
39
+ <span class='highlight blue'> **Marvel** </span>
40
+ and
41
+ <span class='highlight blue'> **DC Comics** </span>
42
+ subreddits.'''
43
+ st.markdown(text, unsafe_allow_html=True)
44
+
45
+ # Area for text input
46
+ import_nltk() # import nltk module if not yet cached in local computer
47
+ new_post = st.text_input('Please copy and paste the subreddit post here', '')
48
+
49
+ # process new input
50
+ def predict_post():
51
+ data = pd.Series(new_post) # pd.Series format new input coz that is the format that predict() recognises
52
+ result = predict(data)
53
+ if result == 1:
54
+ post = 'Marvel'
55
+ if result == 0:
56
+ post = 'DC comics'
57
+ st.write(f'### This post belongs to')
58
+ st.success(f'# {post}')
59
+ st.write(f'### subreddit')
60
+
61
+ # instantiate submit button
62
+ if st.button('Submit'):
63
+ with st.sidebar:
64
+ try:
65
+ predict_post()
66
+ except:
67
+ st.warning('''
68
+ Unable to detect text.
69
+ Please enter text for prediction.
70
+ \n\n Thank you 🙏.
71
+ ''')
final_model.sav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3de8644a134575272a6109b86efca56ec19c92060070e1588cb749dfe01fa3e1
3
+ size 1015414
highlight_text.css ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .highlight {
2
+ border-radius: 0.4rem;
3
+ color: white;
4
+ padding: 0.2rem;
5
+ margin-bottom: 1rem;
6
+ }
7
+
8
+ .bold {
9
+ padding-left: 1rem;
10
+ font-weight: 700;
11
+ }
12
+
13
+ .blue {
14
+ background-color: steelblue;
15
+ }
16
+
17
+ .yellow {
18
+ background-color: goldenrod;
19
+ }
20
+
21
+ .red {
22
+ background-color: lightcoral;
23
+ }
load_css.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ https://discuss.streamlit.io/t/are-you-using-html-in-markdown-tell-us-why/96/25
3
+ """
4
+ import streamlit as st
5
+
6
+ def local_css(file_name):
7
+ with open(file_name) as f:
8
+ st.markdown('<style>{}</style>'.format(f.read()), unsafe_allow_html=True)
model_methods.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from nltk.tokenize import RegexpTokenizer
4
+ from nltk.stem import WordNetLemmatizer
5
+ from nltk.corpus import stopwords
6
+ from sklearn.feature_extraction.text import CountVectorizer
7
+ from sklearn.model_selection import train_test_split
8
+ import re
9
+ import pickle
10
+
11
+ # lemmatizing
12
+ def lemmatize_join(text):
13
+ tokenizer = RegexpTokenizer('[a-z]+', gaps=False) # instantiate tokenizer
14
+ lemmer = WordNetLemmatizer() # instantiate lemmatizer
15
+ return ' '.join([lemmer.lemmatize(w) for w in tokenizer.tokenize(text.lower())])
16
+ # lowercase, join back together with spaces so that word vectorizers can still operate
17
+ # on cell contents as strings
18
+
19
+ def predict(new_data):
20
+ # lemmatize new data
21
+ Z_data = new_data.apply(lemmatize_join)
22
+
23
+ # countvectorize new data
24
+ # import dataset 'full_post' that has been lemmatized
25
+ url = 'https://raw.githubusercontent.com/yxmauw/General_Assembly_Pub/main/project_3/cloud_app/tts.csv'
26
+ df = pd.read_csv(url, header=0)
27
+
28
+ # train-test-split
29
+ X = df['full_post'] # pd.series because dataframe format not friendly for word vectorization
30
+ y = df['subreddit']
31
+
32
+ # make sure target variable has equal representation on both train and test sets
33
+ X_train, X_test, y_train, y_test = train_test_split(X, y,
34
+ test_size=.2,
35
+ stratify=y,
36
+ random_state=42)
37
+ cvec = CountVectorizer()
38
+ Z_train = X_train.apply(lemmatize_join) # lemmatize training data
39
+ cvec.fit(Z_train) # fit on lemmatized training data set
40
+ cvec.transform(Z_data) # transform new data
41
+
42
+ with open('project_3/cloud_app/final_model.sav','rb') as f:
43
+ model = pickle.load(f)
44
+ pred = model.predict(Z_data)
45
+ return pred
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ streamlit==1.11.1
2
+ scikit-learn==1.0.2
3
+ pandas==1.4.2
4
+ numpy==1.21.5
5
+ pillow==9.0.1
6
+ nltk==3.7
subreddit_icon.png ADDED
tts.csv ADDED
The diff for this file is too large to render. See raw diff