Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- .gitattributes +2 -0
- README.md +3 -9
- app.py +263 -0
- doc2vec_model_opinion_corpus (1).d2v +3 -0
- init.py +239 -0
- requirements.txt +0 -0
- review_detection.ipynb +1383 -0
- vercel.json +5 -0
- weights.best.from_scratch1 (1).hdf5 +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
doc2vec_model_opinion_corpus[[:space:]](1).d2v filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
weights.best.from_scratch1[[:space:]](1).hdf5 filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,12 +1,6 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji: 👁
|
| 4 |
-
colorFrom: gray
|
| 5 |
-
colorTo: pink
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 4.16.0
|
| 8 |
app_file: app.py
|
| 9 |
-
|
|
|
|
| 10 |
---
|
| 11 |
-
|
| 12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: deceptive-rev
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
app_file: app.py
|
| 4 |
+
sdk: gradio
|
| 5 |
+
sdk_version: 3.44.4
|
| 6 |
---
|
|
|
|
|
|
app.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, redirect, render_template, request, jsonify
|
| 2 |
+
import requests
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
from gensim.models import Doc2Vec
|
| 7 |
+
import snowballstemmer, re
|
| 8 |
+
from bs4 import BeautifulSoup
|
| 9 |
+
import re, sys
|
| 10 |
+
from tensorflow.keras.models import load_model
|
| 11 |
+
import joblib
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
headers = {
|
| 15 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36, Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.18'
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
app = Flask(__name__)
|
| 19 |
+
|
| 20 |
+
def getsoup(url):
|
| 21 |
+
response = requests.get(url, headers=headers)
|
| 22 |
+
Status_Code = response.status_code
|
| 23 |
+
print(url)
|
| 24 |
+
print(Status_Code)
|
| 25 |
+
|
| 26 |
+
if Status_Code == 200:
|
| 27 |
+
soup = BeautifulSoup(response.content, features="lxml")
|
| 28 |
+
else:
|
| 29 |
+
soup = getsoup(url)
|
| 30 |
+
return soup
|
| 31 |
+
|
| 32 |
+
def getLastPageNumber(soup, site):
|
| 33 |
+
pageNumber = []
|
| 34 |
+
if site == 'flipkart':
|
| 35 |
+
review_number = int(soup.find("span", "_2_R_DZ").text.strip().replace(',', '').split()[-2])
|
| 36 |
+
if review_number <=10:
|
| 37 |
+
lastPage = 1
|
| 38 |
+
else:
|
| 39 |
+
link = soup.find(attrs={"class": "_2MImiq _1Qnn1K"})
|
| 40 |
+
pageNumber = link.find('span').text.strip().replace(',', '').split()
|
| 41 |
+
lastPage1 = pageNumber[len(pageNumber)-1]
|
| 42 |
+
lastPage = int(lastPage1)
|
| 43 |
+
elif site == 'amazon':
|
| 44 |
+
review_number = int(soup.find("div", {"data-hook": "cr-filter-info-review-rating-count"}).text.strip().replace(',', '').split()[-3])
|
| 45 |
+
if review_number <=10:
|
| 46 |
+
lastPage = 1
|
| 47 |
+
else:
|
| 48 |
+
lastPage = review_number // 10
|
| 49 |
+
if lastPage > 500:
|
| 50 |
+
lastPage = 2
|
| 51 |
+
return lastPage
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def geturllist(url, lastPage):
|
| 55 |
+
urllistPages = []
|
| 56 |
+
url = url[:-1]
|
| 57 |
+
for i in range(1,lastPage+1):
|
| 58 |
+
urllistPages.append (url + str(i))
|
| 59 |
+
return urllistPages
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def getReviews(soup, site, url):
|
| 63 |
+
if site == 'flipkart':
|
| 64 |
+
#Extracting the Titles
|
| 65 |
+
title_sec = soup.find_all("p",'_2-N8zT')
|
| 66 |
+
title = []
|
| 67 |
+
for s in title_sec:
|
| 68 |
+
title.append(s.text)
|
| 69 |
+
|
| 70 |
+
author_sec = soup.find_all("p","_2sc7ZR _2V5EHH")
|
| 71 |
+
author = []
|
| 72 |
+
for r in author_sec:
|
| 73 |
+
author.append(r.text)
|
| 74 |
+
|
| 75 |
+
Review_text_sec = soup.find_all("div",'t-ZTKy')
|
| 76 |
+
text = []
|
| 77 |
+
for t in Review_text_sec:
|
| 78 |
+
text.append(t.text)
|
| 79 |
+
|
| 80 |
+
Rating = soup.find_all("div", {"class": ["_3LWZlK _1BLPMq", "_3LWZlK _32lA32 _1BLPMq", "_3LWZlK _1rdVr6 _1BLPMq"]})
|
| 81 |
+
rate = []
|
| 82 |
+
for d in Rating:
|
| 83 |
+
rate.append(d.text)
|
| 84 |
+
|
| 85 |
+
Date_sec = soup.find_all(lambda tag: tag.name == 'p' and tag.get('class') == ['_2sc7ZR'])
|
| 86 |
+
date = []
|
| 87 |
+
for d in Date_sec:
|
| 88 |
+
date.append(d.text)
|
| 89 |
+
|
| 90 |
+
help_sec = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['_1LmwT9'])
|
| 91 |
+
help1 = []
|
| 92 |
+
for d in help_sec:
|
| 93 |
+
help1.append(d.text)
|
| 94 |
+
|
| 95 |
+
elif site == 'amazon':
|
| 96 |
+
n_ = 0
|
| 97 |
+
title_sec = soup.find_all(attrs={"data-hook": "review-title", "class": "a-size-base a-link-normal review-title a-color-base review-title-content a-text-bold"})
|
| 98 |
+
title = []
|
| 99 |
+
for s in title_sec:
|
| 100 |
+
title.append(s.text.replace('\n', ''))
|
| 101 |
+
n_ = len(title)
|
| 102 |
+
|
| 103 |
+
author_sec = soup.find_all(attrs = {"class": "a-profile-name"})
|
| 104 |
+
author = []
|
| 105 |
+
for r in author_sec:
|
| 106 |
+
author.append(r.text)
|
| 107 |
+
while(1):
|
| 108 |
+
if len(author) > n_:
|
| 109 |
+
author.pop(0)
|
| 110 |
+
else:
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
Review_text_sec = soup.find_all(attrs={"data-hook": "review-body", "class": "a-size-base review-text review-text-content"})
|
| 114 |
+
text = []
|
| 115 |
+
for t in Review_text_sec:
|
| 116 |
+
text.append(t.text.replace('\n', ''))
|
| 117 |
+
|
| 118 |
+
Rating = soup.find_all(attrs={"data-hook": "review-star-rating"})
|
| 119 |
+
rate = []
|
| 120 |
+
for d in Rating:
|
| 121 |
+
rate.append(d.text)
|
| 122 |
+
|
| 123 |
+
Date_sec = soup.find_all(attrs={"data-hook": "review-date"})
|
| 124 |
+
date = []
|
| 125 |
+
for d in Date_sec:
|
| 126 |
+
date.append(d.text)
|
| 127 |
+
|
| 128 |
+
help_sec = soup.find_all(attrs={"data-hook": "helpful-vote-statement"})
|
| 129 |
+
help1 = []
|
| 130 |
+
for d in help_sec:
|
| 131 |
+
help1.append(d.text.replace('\n ', ''))
|
| 132 |
+
while(1):
|
| 133 |
+
if len(help1) < n_:
|
| 134 |
+
help1.append(0)
|
| 135 |
+
else:
|
| 136 |
+
break
|
| 137 |
+
|
| 138 |
+
url1 = []
|
| 139 |
+
url1 = [url] * len(date)
|
| 140 |
+
|
| 141 |
+
collate = {'Date': date, 'URL': url1, 'Review_Title': title, 'Author': author, 'Rating': rate, 'Review_text': text, 'Review_helpful': help1}
|
| 142 |
+
collate_df = pd.DataFrame.from_dict(collate)
|
| 143 |
+
return collate_df
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def preprocess_text(text):
|
| 147 |
+
stemmer = snowballstemmer.EnglishStemmer()
|
| 148 |
+
text = " ".join(stemmer.stemWords(re.sub('[!"#%\'()*+,-./:;<=>?@[\\]^_`{|}~1234567890’”“′‘\\\\]', ' ', text).split(' ')))
|
| 149 |
+
stop_words = set(["may", "also", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "across","among", "beside", "however", "yet", "within"] + list('abcdefghijklmnopqrstuvwxyz'))
|
| 150 |
+
stop_list = stemmer.stemWords(stop_words)
|
| 151 |
+
stop_words.update(stop_list)
|
| 152 |
+
text = " ".join(filter(None, filter(lambda word: word not in stop_words, text.lower().split(' '))))
|
| 153 |
+
return text.split(' ')
|
| 154 |
+
|
| 155 |
+
def vectorize_comments_(df, d2v_model):
|
| 156 |
+
y = []
|
| 157 |
+
comments = []
|
| 158 |
+
for i in range(0, len(df)):
|
| 159 |
+
|
| 160 |
+
print(i)
|
| 161 |
+
label = 'SENT_%s' %i
|
| 162 |
+
comments.append(d2v_model.docvecs[label])
|
| 163 |
+
return comments
|
| 164 |
+
|
| 165 |
+
def scraper(url):
|
| 166 |
+
df2 = []
|
| 167 |
+
soup = getsoup(url)
|
| 168 |
+
site = url.split('.')[1]
|
| 169 |
+
if site == 'flipkart':
|
| 170 |
+
url = url + '&page=1'
|
| 171 |
+
elif site == 'amazon':
|
| 172 |
+
url = url + '&pageNumber=1'
|
| 173 |
+
product = url.split('/')[3]
|
| 174 |
+
lastPage = 1
|
| 175 |
+
urllistPages = geturllist(url, lastPage)
|
| 176 |
+
x = 1
|
| 177 |
+
for url in urllistPages:
|
| 178 |
+
soup = getsoup(url)
|
| 179 |
+
df1 = getReviews(soup, site, url)
|
| 180 |
+
if x == 1:
|
| 181 |
+
df3 = []
|
| 182 |
+
df3 = df1
|
| 183 |
+
else:
|
| 184 |
+
df2 = df3
|
| 185 |
+
result = df2.append(df1, ignore_index=True)
|
| 186 |
+
df3 = result
|
| 187 |
+
x += 1
|
| 188 |
+
|
| 189 |
+
loaded_model = load_model('weights.best.from_scratch1 (1).hdf5')
|
| 190 |
+
|
| 191 |
+
preprocessed_arr = [preprocess_text(x) for x in list(df3['Review_text'])]
|
| 192 |
+
|
| 193 |
+
doc2vec_model = Doc2Vec.load("doc2vec_model_opinion_corpus (1).d2v")
|
| 194 |
+
|
| 195 |
+
textData = vectorize_comments_(preprocessed_arr, doc2vec_model)
|
| 196 |
+
|
| 197 |
+
textData_array = np.array(textData)
|
| 198 |
+
|
| 199 |
+
num_vectors = textData_array.shape[0]
|
| 200 |
+
textData_3d = textData_array.reshape((num_vectors, 1, -1))
|
| 201 |
+
|
| 202 |
+
new_shape = (textData_array.shape[0], 380, 512)
|
| 203 |
+
|
| 204 |
+
X_test3_reshaped = np.zeros(new_shape, dtype=textData_3d.dtype)
|
| 205 |
+
X_test3_reshaped[:, :textData_3d.shape[1], :textData_3d.shape[2]] = textData_3d
|
| 206 |
+
|
| 207 |
+
predictions = np.rint(loaded_model.predict(X_test3_reshaped))
|
| 208 |
+
|
| 209 |
+
argMax = []
|
| 210 |
+
|
| 211 |
+
for i in predictions:
|
| 212 |
+
argMax.append(np.argmax(i))
|
| 213 |
+
|
| 214 |
+
print(argMax)
|
| 215 |
+
print(list(df3['Review_text'])[3])
|
| 216 |
+
|
| 217 |
+
arr = []
|
| 218 |
+
for i, j in enumerate(argMax):
|
| 219 |
+
if j == 2 or j == 1:
|
| 220 |
+
arr.append(list(df3['Review_text'])[i])
|
| 221 |
+
return arr
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# @app.route('/', methods=['GET'])
|
| 225 |
+
# def index():
|
| 226 |
+
# results = []
|
| 227 |
+
# if request.args.get('url'):
|
| 228 |
+
# results = scraper(request.args.get('url'))
|
| 229 |
+
# return results
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# if __name__ == "__main__":
|
| 233 |
+
# app.run(debug=True)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def index():
|
| 238 |
+
results = []
|
| 239 |
+
if request.args.get('url'):
|
| 240 |
+
results = scraper(request.args.get('url'))
|
| 241 |
+
return results
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
inputs_image_url = [
|
| 245 |
+
gr.Textbox(type="text", label="Image URL"),
|
| 246 |
+
]
|
| 247 |
+
|
| 248 |
+
outputs_result_dict = [
|
| 249 |
+
gr.Textbox(type="text", label="Result Dictionary"),
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
interface_image_url = gr.Interface(
|
| 253 |
+
fn=index,
|
| 254 |
+
inputs=inputs_image_url,
|
| 255 |
+
outputs=outputs_result_dict,
|
| 256 |
+
title="Dark review detection",
|
| 257 |
+
cache_examples=False,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
gr.TabbedInterface(
|
| 261 |
+
[interface_image_url],
|
| 262 |
+
tab_names=['Reviews inference']
|
| 263 |
+
).queue().launch()
|
doc2vec_model_opinion_corpus (1).d2v
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:deabad8d2bf4677f8f6f7069da1f928f6ce1fe45722f0839c99a2615f37f28ea
|
| 3 |
+
size 29196813
|
init.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from string import ascii_lowercase
|
| 4 |
+
from gensim.models import Doc2Vec
|
| 5 |
+
from gensim.models import doc2vec
|
| 6 |
+
from gensim.models import KeyedVectors
|
| 7 |
+
import snowballstemmer, re
|
| 8 |
+
import requests
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
import re, sys
|
| 11 |
+
from tensorflow.keras.models import load_model
|
| 12 |
+
import joblib
|
| 13 |
+
|
| 14 |
+
headers = {
|
| 15 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36, Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.18'
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
def getsoup(url):
|
| 19 |
+
response = requests.get(url, headers=headers)
|
| 20 |
+
Status_Code = response.status_code
|
| 21 |
+
print(url)
|
| 22 |
+
print(Status_Code)
|
| 23 |
+
|
| 24 |
+
if Status_Code == 200:
|
| 25 |
+
soup = BeautifulSoup(response.content, features="lxml")
|
| 26 |
+
else:
|
| 27 |
+
soup = getsoup(url)
|
| 28 |
+
return soup
|
| 29 |
+
|
| 30 |
+
#Get Last Page number
|
| 31 |
+
def getLastPageNumber(soup, site):
|
| 32 |
+
pageNumber = []
|
| 33 |
+
if site == 'flipkart':
|
| 34 |
+
review_number = int(soup.find("span", "_2_R_DZ").text.strip().replace(',', '').split()[-2])
|
| 35 |
+
if review_number <=10:
|
| 36 |
+
lastPage = 1
|
| 37 |
+
else:
|
| 38 |
+
link = soup.find(attrs={"class": "_2MImiq _1Qnn1K"})
|
| 39 |
+
pageNumber = link.find('span').text.strip().replace(',', '').split()
|
| 40 |
+
lastPage1 = pageNumber[len(pageNumber)-1]
|
| 41 |
+
lastPage = int(lastPage1)
|
| 42 |
+
elif site == 'amazon':
|
| 43 |
+
review_number = int(soup.find("div", {"data-hook": "cr-filter-info-review-rating-count"}).text.strip().replace(',', '').split()[-3])
|
| 44 |
+
if review_number <=10:
|
| 45 |
+
lastPage = 1
|
| 46 |
+
else:
|
| 47 |
+
lastPage = review_number // 10
|
| 48 |
+
if lastPage > 500:
|
| 49 |
+
lastPage = 2
|
| 50 |
+
return lastPage
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def geturllist(url, lastPage):
|
| 54 |
+
urllistPages = []
|
| 55 |
+
url = url[:-1]
|
| 56 |
+
for i in range(1,lastPage+1):
|
| 57 |
+
urllistPages.append (url + str(i))
|
| 58 |
+
return urllistPages
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def getReviews(soup, site, url):
|
| 62 |
+
if site == 'flipkart':
|
| 63 |
+
#Extracting the Titles
|
| 64 |
+
title_sec = soup.find_all("p",'_2-N8zT')
|
| 65 |
+
title = []
|
| 66 |
+
for s in title_sec:
|
| 67 |
+
title.append(s.text)
|
| 68 |
+
|
| 69 |
+
#Extracting the Author names
|
| 70 |
+
author_sec = soup.find_all("p","_2sc7ZR _2V5EHH")
|
| 71 |
+
author = []
|
| 72 |
+
for r in author_sec:
|
| 73 |
+
author.append(r.text)
|
| 74 |
+
|
| 75 |
+
#Extracting the Text
|
| 76 |
+
Review_text_sec = soup.find_all("div",'t-ZTKy')
|
| 77 |
+
text = []
|
| 78 |
+
for t in Review_text_sec:
|
| 79 |
+
text.append(t.text)
|
| 80 |
+
|
| 81 |
+
#Extracting the Star rating
|
| 82 |
+
Rating = soup.find_all("div", {"class": ["_3LWZlK _1BLPMq", "_3LWZlK _32lA32 _1BLPMq", "_3LWZlK _1rdVr6 _1BLPMq"]})
|
| 83 |
+
rate = []
|
| 84 |
+
for d in Rating:
|
| 85 |
+
rate.append(d.text)
|
| 86 |
+
|
| 87 |
+
#Extracting the Date
|
| 88 |
+
Date_sec = soup.find_all(lambda tag: tag.name == 'p' and tag.get('class') == ['_2sc7ZR'])
|
| 89 |
+
date = []
|
| 90 |
+
for d in Date_sec:
|
| 91 |
+
date.append(d.text)
|
| 92 |
+
|
| 93 |
+
#Extracting the Helpful rating
|
| 94 |
+
help_sec = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['_1LmwT9'])
|
| 95 |
+
help1 = []
|
| 96 |
+
for d in help_sec:
|
| 97 |
+
help1.append(d.text)
|
| 98 |
+
|
| 99 |
+
elif site == 'amazon':
|
| 100 |
+
n_ = 0
|
| 101 |
+
title_sec = soup.find_all(attrs={"data-hook": "review-title", "class": "a-size-base a-link-normal review-title a-color-base review-title-content a-text-bold"})
|
| 102 |
+
title = []
|
| 103 |
+
for s in title_sec:
|
| 104 |
+
title.append(s.text.replace('\n', ''))
|
| 105 |
+
n_ = len(title)
|
| 106 |
+
|
| 107 |
+
author_sec = soup.find_all(attrs = {"class": "a-profile-name"})
|
| 108 |
+
author = []
|
| 109 |
+
for r in author_sec:
|
| 110 |
+
author.append(r.text)
|
| 111 |
+
while(1):
|
| 112 |
+
if len(author) > n_:
|
| 113 |
+
author.pop(0)
|
| 114 |
+
else:
|
| 115 |
+
break
|
| 116 |
+
|
| 117 |
+
Review_text_sec = soup.find_all(attrs={"data-hook": "review-body", "class": "a-size-base review-text review-text-content"})
|
| 118 |
+
text = []
|
| 119 |
+
for t in Review_text_sec:
|
| 120 |
+
text.append(t.text.replace('\n', ''))
|
| 121 |
+
|
| 122 |
+
Rating = soup.find_all(attrs={"data-hook": "review-star-rating"})
|
| 123 |
+
rate = []
|
| 124 |
+
for d in Rating:
|
| 125 |
+
rate.append(d.text)
|
| 126 |
+
|
| 127 |
+
Date_sec = soup.find_all(attrs={"data-hook": "review-date"})
|
| 128 |
+
date = []
|
| 129 |
+
for d in Date_sec:
|
| 130 |
+
date.append(d.text)
|
| 131 |
+
|
| 132 |
+
help_sec = soup.find_all(attrs={"data-hook": "helpful-vote-statement"})
|
| 133 |
+
help1 = []
|
| 134 |
+
for d in help_sec:
|
| 135 |
+
help1.append(d.text.replace('\n ', ''))
|
| 136 |
+
while(1):
|
| 137 |
+
if len(help1) < n_:
|
| 138 |
+
help1.append(0)
|
| 139 |
+
else:
|
| 140 |
+
break
|
| 141 |
+
|
| 142 |
+
url1 = []
|
| 143 |
+
url1 = [url] * len(date)
|
| 144 |
+
|
| 145 |
+
collate = {'Date': date, 'URL': url1, 'Review_Title': title, 'Author': author, 'Rating': rate, 'Review_text': text, 'Review_helpful': help1}
|
| 146 |
+
collate_df = pd.DataFrame.from_dict(collate)
|
| 147 |
+
return collate_df
|
| 148 |
+
|
| 149 |
+
def scraper(url):
|
| 150 |
+
df2 = []
|
| 151 |
+
soup = getsoup(url)
|
| 152 |
+
site = url.split('.')[1]
|
| 153 |
+
if site == 'flipkart':
|
| 154 |
+
url = url + '&page=1'
|
| 155 |
+
elif site == 'amazon':
|
| 156 |
+
url = url + '&pageNumber=1'
|
| 157 |
+
product = url.split('/')[3]
|
| 158 |
+
lastPage = 1
|
| 159 |
+
urllistPages = geturllist(url, lastPage)
|
| 160 |
+
x = 1
|
| 161 |
+
for url in urllistPages:
|
| 162 |
+
soup = getsoup(url)
|
| 163 |
+
df1 = getReviews(soup, site, url)
|
| 164 |
+
if x == 1:
|
| 165 |
+
df3 = []
|
| 166 |
+
df3 = df1
|
| 167 |
+
else:
|
| 168 |
+
df2 = df3
|
| 169 |
+
result = df2.append(df1, ignore_index=True)
|
| 170 |
+
df3 = result
|
| 171 |
+
x += 1
|
| 172 |
+
print(list(df3['Review_text']))
|
| 173 |
+
return list(df3['Review_text'])
|
| 174 |
+
|
| 175 |
+
arr = scraper('https://www.amazon.in/Redmi-inches-Ready-Smart-L32R8-FVIN/product-review/B0BVMLNGXR/ref=lp_90117314031_1_1?pf_rd_p=9e034799-55e2-4ab2-b0d0-eb42f95b2d05&pf_rd_r=V81TJ2VTRM0BYHQ6XX8S&sbo=RZvfv%2F%2FHxDF%2BO5021pAnSA%3D%3D&th=1')
|
| 176 |
+
|
| 177 |
+
TaggedDocument = doc2vec.TaggedDocument
|
| 178 |
+
|
| 179 |
+
loaded_model = load_model('weights.best.from_scratch1 (1).hdf5')
|
| 180 |
+
|
| 181 |
+
def preprocess_text(text):
|
| 182 |
+
stemmer = snowballstemmer.EnglishStemmer()
|
| 183 |
+
text = " ".join(stemmer.stemWords(re.sub('[!"#%\'()*+,-./:;<=>?@[\\]^_`{|}~1234567890’”“′‘\\\\]', ' ', text).split(' ')))
|
| 184 |
+
|
| 185 |
+
stop_words = set(["may", "also", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "across", "among", "beside", "however", "yet", "within"] + list(ascii_lowercase))
|
| 186 |
+
stop_list = stemmer.stemWords(stop_words)
|
| 187 |
+
stop_words.update(stop_list)
|
| 188 |
+
text = " ".join(filter(None, filter(lambda word: word not in stop_words, text.lower().split(' '))))
|
| 189 |
+
|
| 190 |
+
return text.split(' ')
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# arr = ['This is not a nice product', 'This is brilliant product', "I have had this tv for a year and a half. The tv worked smoothly and recently, it's display stopped working. I have contacted the company and they assured a repair within 8-10 days replacing the display panel. Then came the worst after sale experience I had ever. They didn't respond to my calls and whenever, I raised a grievance, I was just given different dates and extensions.", ''' In monotheistic belief systems, God is usually viewed as the supreme being, creator, and principal object of faith. In polytheistic belief systems, a god is "a spirit or being believed to have created, or for controlling some part of the universe or life, for which such a deity is often worshipped ''']
|
| 194 |
+
|
| 195 |
+
preprocessed_arr = [preprocess_text(x) for x in arr]
|
| 196 |
+
|
| 197 |
+
doc2vec_model = Doc2Vec.load("doc2vec_model_opinion_corpus (1).d2v")
|
| 198 |
+
|
| 199 |
+
def vectorize_comments_(df, d2v_model):
|
| 200 |
+
y = []
|
| 201 |
+
comments = []
|
| 202 |
+
for i in range(0, len(df)):
|
| 203 |
+
print(i)
|
| 204 |
+
label = 'SENT_%s' %i
|
| 205 |
+
comments.append(d2v_model.docvecs[label])
|
| 206 |
+
|
| 207 |
+
return comments
|
| 208 |
+
|
| 209 |
+
textData = vectorize_comments_(preprocessed_arr, doc2vec_model)
|
| 210 |
+
|
| 211 |
+
import numpy as np
|
| 212 |
+
|
| 213 |
+
textData_array = np.array(textData)
|
| 214 |
+
|
| 215 |
+
num_vectors = textData_array.shape[0]
|
| 216 |
+
textData_3d = textData_array.reshape((num_vectors, 1, -1))
|
| 217 |
+
|
| 218 |
+
new_shape = (textData_array.shape[0], 380, 512)
|
| 219 |
+
|
| 220 |
+
X_test3_reshaped = np.zeros(new_shape, dtype=textData_3d.dtype)
|
| 221 |
+
X_test3_reshaped[:, :textData_3d.shape[1], :textData_3d.shape[2]] = textData_3d
|
| 222 |
+
|
| 223 |
+
predictions = np.rint(loaded_model.predict(X_test3_reshaped))
|
| 224 |
+
|
| 225 |
+
argMax = []
|
| 226 |
+
|
| 227 |
+
for i in predictions:
|
| 228 |
+
argMax.append(np.argmax(i))
|
| 229 |
+
|
| 230 |
+
def returnRequirements(comments, preds):
|
| 231 |
+
arr = []
|
| 232 |
+
for i, j in enumerate(preds):
|
| 233 |
+
if j == 3 or j == 0:
|
| 234 |
+
arr.append(comments[i])
|
| 235 |
+
return arr
|
| 236 |
+
|
| 237 |
+
# 3 & 0 is deceptive rest aren't
|
| 238 |
+
print(argMax)
|
| 239 |
+
print(returnRequirements(arr, argMax))
|
requirements.txt
ADDED
|
Binary file (790 Bytes). View file
|
|
|
review_detection.ipynb
ADDED
|
@@ -0,0 +1,1383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"colab": {
|
| 8 |
+
"base_uri": "https://localhost:8080/"
|
| 9 |
+
},
|
| 10 |
+
"id": "aqGqpcYIpf_q",
|
| 11 |
+
"outputId": "a6d87acc-4df9-4abf-973c-c791c5461af9"
|
| 12 |
+
},
|
| 13 |
+
"outputs": [
|
| 14 |
+
{
|
| 15 |
+
"name": "stdout",
|
| 16 |
+
"output_type": "stream",
|
| 17 |
+
"text": [
|
| 18 |
+
"Downloading deceptive-opinion-spam-corpus.zip to /content\n",
|
| 19 |
+
"\r 0% 0.00/456k [00:00<?, ?B/s]\n",
|
| 20 |
+
"\r100% 456k/456k [00:00<00:00, 111MB/s]\n"
|
| 21 |
+
]
|
| 22 |
+
}
|
| 23 |
+
],
|
| 24 |
+
"source": [
|
| 25 |
+
"!kaggle datasets download -d rtatman/deceptive-opinion-spam-corpus"
|
| 26 |
+
]
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"metadata": {
|
| 32 |
+
"id": "zu4NTMHapmms"
|
| 33 |
+
},
|
| 34 |
+
"outputs": [],
|
| 35 |
+
"source": [
|
| 36 |
+
"import zipfile\n",
|
| 37 |
+
"zip_ref = zipfile.ZipFile('/content/deceptive-opinion-spam-corpus.zip', 'r')\n",
|
| 38 |
+
"zip_ref.extractall('/content')\n",
|
| 39 |
+
"zip_ref.close()"
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"metadata": {
|
| 46 |
+
"id": "3hIl0gHep9q6"
|
| 47 |
+
},
|
| 48 |
+
"outputs": [],
|
| 49 |
+
"source": [
|
| 50 |
+
"import pandas as pd\n",
|
| 51 |
+
"import numpy as np\n",
|
| 52 |
+
"from keras.preprocessing import sequence\n",
|
| 53 |
+
"from keras.layers import TimeDistributed, GlobalAveragePooling1D, GlobalAveragePooling2D, BatchNormalization\n",
|
| 54 |
+
"from keras.layers import LSTM\n",
|
| 55 |
+
"from keras.layers import Conv1D, MaxPooling1D, Conv2D, MaxPooling2D, AveragePooling1D\n",
|
| 56 |
+
"from keras.layers import Embedding\n",
|
| 57 |
+
"from keras.layers import Dropout, Flatten, Bidirectional, Dense, Activation, TimeDistributed\n",
|
| 58 |
+
"from keras.models import Model, Sequential\n",
|
| 59 |
+
"from tensorflow.keras.utils import to_categorical\n",
|
| 60 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 61 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 62 |
+
"from nltk.corpus import stopwords\n",
|
| 63 |
+
"from nltk.tokenize import word_tokenize, sent_tokenize\n",
|
| 64 |
+
"from nltk.stem.wordnet import WordNetLemmatizer\n",
|
| 65 |
+
"from string import ascii_lowercase\n",
|
| 66 |
+
"from collections import Counter\n",
|
| 67 |
+
"from gensim.models import Word2Vec\n",
|
| 68 |
+
"from gensim.models import Doc2Vec\n",
|
| 69 |
+
"from gensim.models import doc2vec\n",
|
| 70 |
+
"from gensim.models import KeyedVectors\n",
|
| 71 |
+
"import itertools, nltk, snowballstemmer, re\n",
|
| 72 |
+
"import random\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"TaggedDocument = doc2vec.TaggedDocument"
|
| 75 |
+
]
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"metadata": {
|
| 81 |
+
"id": "fzwpJb7EqCjc"
|
| 82 |
+
},
|
| 83 |
+
"outputs": [],
|
| 84 |
+
"source": [
|
| 85 |
+
"class LabeledLineSentence(object):\n",
|
| 86 |
+
" def __init__(self, sources):\n",
|
| 87 |
+
" self.sources = sources\n",
|
| 88 |
+
"\n",
|
| 89 |
+
" flipped = {}\n",
|
| 90 |
+
"\n",
|
| 91 |
+
" for key, value in sources.items():\n",
|
| 92 |
+
" if value not in flipped:\n",
|
| 93 |
+
" flipped[value] = [key]\n",
|
| 94 |
+
" else:\n",
|
| 95 |
+
" raise Exception('Non-unique prefix encountered')\n",
|
| 96 |
+
"\n",
|
| 97 |
+
" def __iter__(self):\n",
|
| 98 |
+
" for source, prefix in self.sources.items():\n",
|
| 99 |
+
" with utils.smart_open(source) as fin:\n",
|
| 100 |
+
" for item_no, line in enumerate(fin):\n",
|
| 101 |
+
" yield TaggedDocument(utils.to_unicode(line).split(), [prefix + '_%s' % item_no])\n",
|
| 102 |
+
"\n",
|
| 103 |
+
" def to_array(self):\n",
|
| 104 |
+
" self.sentences = []\n",
|
| 105 |
+
" for source, prefix in self.sources.items():\n",
|
| 106 |
+
" with utils.smart_open(source) as fin:\n",
|
| 107 |
+
" for item_no, line in enumerate(fin):\n",
|
| 108 |
+
" self.sentences.append(TaggedDocument(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))\n",
|
| 109 |
+
" return self.sentences\n",
|
| 110 |
+
"\n",
|
| 111 |
+
" def sentences_perm(self):\n",
|
| 112 |
+
" shuffled = list(self.sentences)\n",
|
| 113 |
+
" random.shuffle(shuffled)\n",
|
| 114 |
+
" return shuffled"
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"metadata": {
|
| 121 |
+
"id": "e_auMclPqmrI"
|
| 122 |
+
},
|
| 123 |
+
"outputs": [],
|
| 124 |
+
"source": [
|
| 125 |
+
"data = pd.read_csv(\"/content/deceptive-opinion.csv\")"
|
| 126 |
+
]
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"metadata": {
|
| 132 |
+
"id": "G-EIqcKVrbEl"
|
| 133 |
+
},
|
| 134 |
+
"outputs": [],
|
| 135 |
+
"source": [
|
| 136 |
+
"data['polarity'] = np.where(data['polarity']=='positive', 1, 0)\n",
|
| 137 |
+
"data['deceptive'] = np.where(data['deceptive']=='truthful', 1, 0)"
|
| 138 |
+
]
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"metadata": {
|
| 144 |
+
"colab": {
|
| 145 |
+
"base_uri": "https://localhost:8080/",
|
| 146 |
+
"height": 300
|
| 147 |
+
},
|
| 148 |
+
"id": "2REEjGj9rck1",
|
| 149 |
+
"outputId": "a5679d0f-f0b9-4c21-8005-42058e2cc4fc"
|
| 150 |
+
},
|
| 151 |
+
"outputs": [
|
| 152 |
+
{
|
| 153 |
+
"data": {
|
| 154 |
+
"text/html": [
|
| 155 |
+
"\n",
|
| 156 |
+
" <div id=\"df-6614128d-b81e-41f1-9a92-25467585644c\" class=\"colab-df-container\">\n",
|
| 157 |
+
" <div>\n",
|
| 158 |
+
"<style scoped>\n",
|
| 159 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 160 |
+
" vertical-align: middle;\n",
|
| 161 |
+
" }\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" .dataframe tbody tr th {\n",
|
| 164 |
+
" vertical-align: top;\n",
|
| 165 |
+
" }\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" .dataframe thead th {\n",
|
| 168 |
+
" text-align: right;\n",
|
| 169 |
+
" }\n",
|
| 170 |
+
"</style>\n",
|
| 171 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 172 |
+
" <thead>\n",
|
| 173 |
+
" <tr style=\"text-align: right;\">\n",
|
| 174 |
+
" <th></th>\n",
|
| 175 |
+
" <th>deceptive</th>\n",
|
| 176 |
+
" <th>polarity</th>\n",
|
| 177 |
+
" </tr>\n",
|
| 178 |
+
" </thead>\n",
|
| 179 |
+
" <tbody>\n",
|
| 180 |
+
" <tr>\n",
|
| 181 |
+
" <th>count</th>\n",
|
| 182 |
+
" <td>1600.000000</td>\n",
|
| 183 |
+
" <td>1600.000000</td>\n",
|
| 184 |
+
" </tr>\n",
|
| 185 |
+
" <tr>\n",
|
| 186 |
+
" <th>mean</th>\n",
|
| 187 |
+
" <td>0.500000</td>\n",
|
| 188 |
+
" <td>0.500000</td>\n",
|
| 189 |
+
" </tr>\n",
|
| 190 |
+
" <tr>\n",
|
| 191 |
+
" <th>std</th>\n",
|
| 192 |
+
" <td>0.500156</td>\n",
|
| 193 |
+
" <td>0.500156</td>\n",
|
| 194 |
+
" </tr>\n",
|
| 195 |
+
" <tr>\n",
|
| 196 |
+
" <th>min</th>\n",
|
| 197 |
+
" <td>0.000000</td>\n",
|
| 198 |
+
" <td>0.000000</td>\n",
|
| 199 |
+
" </tr>\n",
|
| 200 |
+
" <tr>\n",
|
| 201 |
+
" <th>25%</th>\n",
|
| 202 |
+
" <td>0.000000</td>\n",
|
| 203 |
+
" <td>0.000000</td>\n",
|
| 204 |
+
" </tr>\n",
|
| 205 |
+
" <tr>\n",
|
| 206 |
+
" <th>50%</th>\n",
|
| 207 |
+
" <td>0.500000</td>\n",
|
| 208 |
+
" <td>0.500000</td>\n",
|
| 209 |
+
" </tr>\n",
|
| 210 |
+
" <tr>\n",
|
| 211 |
+
" <th>75%</th>\n",
|
| 212 |
+
" <td>1.000000</td>\n",
|
| 213 |
+
" <td>1.000000</td>\n",
|
| 214 |
+
" </tr>\n",
|
| 215 |
+
" <tr>\n",
|
| 216 |
+
" <th>max</th>\n",
|
| 217 |
+
" <td>1.000000</td>\n",
|
| 218 |
+
" <td>1.000000</td>\n",
|
| 219 |
+
" </tr>\n",
|
| 220 |
+
" </tbody>\n",
|
| 221 |
+
"</table>\n",
|
| 222 |
+
"</div>\n",
|
| 223 |
+
" <div class=\"colab-df-buttons\">\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" <div class=\"colab-df-container\">\n",
|
| 226 |
+
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-6614128d-b81e-41f1-9a92-25467585644c')\"\n",
|
| 227 |
+
" title=\"Convert this dataframe to an interactive table.\"\n",
|
| 228 |
+
" style=\"display:none;\">\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
|
| 231 |
+
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
|
| 232 |
+
" </svg>\n",
|
| 233 |
+
" </button>\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" <style>\n",
|
| 236 |
+
" .colab-df-container {\n",
|
| 237 |
+
" display:flex;\n",
|
| 238 |
+
" gap: 12px;\n",
|
| 239 |
+
" }\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" .colab-df-convert {\n",
|
| 242 |
+
" background-color: #E8F0FE;\n",
|
| 243 |
+
" border: none;\n",
|
| 244 |
+
" border-radius: 50%;\n",
|
| 245 |
+
" cursor: pointer;\n",
|
| 246 |
+
" display: none;\n",
|
| 247 |
+
" fill: #1967D2;\n",
|
| 248 |
+
" height: 32px;\n",
|
| 249 |
+
" padding: 0 0 0 0;\n",
|
| 250 |
+
" width: 32px;\n",
|
| 251 |
+
" }\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" .colab-df-convert:hover {\n",
|
| 254 |
+
" background-color: #E2EBFA;\n",
|
| 255 |
+
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 256 |
+
" fill: #174EA6;\n",
|
| 257 |
+
" }\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" .colab-df-buttons div {\n",
|
| 260 |
+
" margin-bottom: 4px;\n",
|
| 261 |
+
" }\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" [theme=dark] .colab-df-convert {\n",
|
| 264 |
+
" background-color: #3B4455;\n",
|
| 265 |
+
" fill: #D2E3FC;\n",
|
| 266 |
+
" }\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" [theme=dark] .colab-df-convert:hover {\n",
|
| 269 |
+
" background-color: #434B5C;\n",
|
| 270 |
+
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
|
| 271 |
+
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
|
| 272 |
+
" fill: #FFFFFF;\n",
|
| 273 |
+
" }\n",
|
| 274 |
+
" </style>\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" <script>\n",
|
| 277 |
+
" const buttonEl =\n",
|
| 278 |
+
" document.querySelector('#df-6614128d-b81e-41f1-9a92-25467585644c button.colab-df-convert');\n",
|
| 279 |
+
" buttonEl.style.display =\n",
|
| 280 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" async function convertToInteractive(key) {\n",
|
| 283 |
+
" const element = document.querySelector('#df-6614128d-b81e-41f1-9a92-25467585644c');\n",
|
| 284 |
+
" const dataTable =\n",
|
| 285 |
+
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
|
| 286 |
+
" [key], {});\n",
|
| 287 |
+
" if (!dataTable) return;\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
|
| 290 |
+
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
|
| 291 |
+
" + ' to learn more about interactive tables.';\n",
|
| 292 |
+
" element.innerHTML = '';\n",
|
| 293 |
+
" dataTable['output_type'] = 'display_data';\n",
|
| 294 |
+
" await google.colab.output.renderOutput(dataTable, element);\n",
|
| 295 |
+
" const docLink = document.createElement('div');\n",
|
| 296 |
+
" docLink.innerHTML = docLinkHtml;\n",
|
| 297 |
+
" element.appendChild(docLink);\n",
|
| 298 |
+
" }\n",
|
| 299 |
+
" </script>\n",
|
| 300 |
+
" </div>\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"<div id=\"df-cc66d435-72a8-4146-ba22-ea8ef5610445\">\n",
|
| 304 |
+
" <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-cc66d435-72a8-4146-ba22-ea8ef5610445')\"\n",
|
| 305 |
+
" title=\"Suggest charts\"\n",
|
| 306 |
+
" style=\"display:none;\">\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
|
| 309 |
+
" width=\"24px\">\n",
|
| 310 |
+
" <g>\n",
|
| 311 |
+
" <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
|
| 312 |
+
" </g>\n",
|
| 313 |
+
"</svg>\n",
|
| 314 |
+
" </button>\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"<style>\n",
|
| 317 |
+
" .colab-df-quickchart {\n",
|
| 318 |
+
" --bg-color: #E8F0FE;\n",
|
| 319 |
+
" --fill-color: #1967D2;\n",
|
| 320 |
+
" --hover-bg-color: #E2EBFA;\n",
|
| 321 |
+
" --hover-fill-color: #174EA6;\n",
|
| 322 |
+
" --disabled-fill-color: #AAA;\n",
|
| 323 |
+
" --disabled-bg-color: #DDD;\n",
|
| 324 |
+
" }\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" [theme=dark] .colab-df-quickchart {\n",
|
| 327 |
+
" --bg-color: #3B4455;\n",
|
| 328 |
+
" --fill-color: #D2E3FC;\n",
|
| 329 |
+
" --hover-bg-color: #434B5C;\n",
|
| 330 |
+
" --hover-fill-color: #FFFFFF;\n",
|
| 331 |
+
" --disabled-bg-color: #3B4455;\n",
|
| 332 |
+
" --disabled-fill-color: #666;\n",
|
| 333 |
+
" }\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" .colab-df-quickchart {\n",
|
| 336 |
+
" background-color: var(--bg-color);\n",
|
| 337 |
+
" border: none;\n",
|
| 338 |
+
" border-radius: 50%;\n",
|
| 339 |
+
" cursor: pointer;\n",
|
| 340 |
+
" display: none;\n",
|
| 341 |
+
" fill: var(--fill-color);\n",
|
| 342 |
+
" height: 32px;\n",
|
| 343 |
+
" padding: 0;\n",
|
| 344 |
+
" width: 32px;\n",
|
| 345 |
+
" }\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" .colab-df-quickchart:hover {\n",
|
| 348 |
+
" background-color: var(--hover-bg-color);\n",
|
| 349 |
+
" box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 350 |
+
" fill: var(--button-hover-fill-color);\n",
|
| 351 |
+
" }\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" .colab-df-quickchart-complete:disabled,\n",
|
| 354 |
+
" .colab-df-quickchart-complete:disabled:hover {\n",
|
| 355 |
+
" background-color: var(--disabled-bg-color);\n",
|
| 356 |
+
" fill: var(--disabled-fill-color);\n",
|
| 357 |
+
" box-shadow: none;\n",
|
| 358 |
+
" }\n",
|
| 359 |
+
"\n",
|
| 360 |
+
" .colab-df-spinner {\n",
|
| 361 |
+
" border: 2px solid var(--fill-color);\n",
|
| 362 |
+
" border-color: transparent;\n",
|
| 363 |
+
" border-bottom-color: var(--fill-color);\n",
|
| 364 |
+
" animation:\n",
|
| 365 |
+
" spin 1s steps(1) infinite;\n",
|
| 366 |
+
" }\n",
|
| 367 |
+
"\n",
|
| 368 |
+
" @keyframes spin {\n",
|
| 369 |
+
" 0% {\n",
|
| 370 |
+
" border-color: transparent;\n",
|
| 371 |
+
" border-bottom-color: var(--fill-color);\n",
|
| 372 |
+
" border-left-color: var(--fill-color);\n",
|
| 373 |
+
" }\n",
|
| 374 |
+
" 20% {\n",
|
| 375 |
+
" border-color: transparent;\n",
|
| 376 |
+
" border-left-color: var(--fill-color);\n",
|
| 377 |
+
" border-top-color: var(--fill-color);\n",
|
| 378 |
+
" }\n",
|
| 379 |
+
" 30% {\n",
|
| 380 |
+
" border-color: transparent;\n",
|
| 381 |
+
" border-left-color: var(--fill-color);\n",
|
| 382 |
+
" border-top-color: var(--fill-color);\n",
|
| 383 |
+
" border-right-color: var(--fill-color);\n",
|
| 384 |
+
" }\n",
|
| 385 |
+
" 40% {\n",
|
| 386 |
+
" border-color: transparent;\n",
|
| 387 |
+
" border-right-color: var(--fill-color);\n",
|
| 388 |
+
" border-top-color: var(--fill-color);\n",
|
| 389 |
+
" }\n",
|
| 390 |
+
" 60% {\n",
|
| 391 |
+
" border-color: transparent;\n",
|
| 392 |
+
" border-right-color: var(--fill-color);\n",
|
| 393 |
+
" }\n",
|
| 394 |
+
" 80% {\n",
|
| 395 |
+
" border-color: transparent;\n",
|
| 396 |
+
" border-right-color: var(--fill-color);\n",
|
| 397 |
+
" border-bottom-color: var(--fill-color);\n",
|
| 398 |
+
" }\n",
|
| 399 |
+
" 90% {\n",
|
| 400 |
+
" border-color: transparent;\n",
|
| 401 |
+
" border-bottom-color: var(--fill-color);\n",
|
| 402 |
+
" }\n",
|
| 403 |
+
" }\n",
|
| 404 |
+
"</style>\n",
|
| 405 |
+
"\n",
|
| 406 |
+
" <script>\n",
|
| 407 |
+
" async function quickchart(key) {\n",
|
| 408 |
+
" const quickchartButtonEl =\n",
|
| 409 |
+
" document.querySelector('#' + key + ' button');\n",
|
| 410 |
+
" quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n",
|
| 411 |
+
" quickchartButtonEl.classList.add('colab-df-spinner');\n",
|
| 412 |
+
" try {\n",
|
| 413 |
+
" const charts = await google.colab.kernel.invokeFunction(\n",
|
| 414 |
+
" 'suggestCharts', [key], {});\n",
|
| 415 |
+
" } catch (error) {\n",
|
| 416 |
+
" console.error('Error during call to suggestCharts:', error);\n",
|
| 417 |
+
" }\n",
|
| 418 |
+
" quickchartButtonEl.classList.remove('colab-df-spinner');\n",
|
| 419 |
+
" quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
|
| 420 |
+
" }\n",
|
| 421 |
+
" (() => {\n",
|
| 422 |
+
" let quickchartButtonEl =\n",
|
| 423 |
+
" document.querySelector('#df-cc66d435-72a8-4146-ba22-ea8ef5610445 button');\n",
|
| 424 |
+
" quickchartButtonEl.style.display =\n",
|
| 425 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 426 |
+
" })();\n",
|
| 427 |
+
" </script>\n",
|
| 428 |
+
"</div>\n",
|
| 429 |
+
"\n",
|
| 430 |
+
" </div>\n",
|
| 431 |
+
" </div>\n"
|
| 432 |
+
],
|
| 433 |
+
"text/plain": [
|
| 434 |
+
" deceptive polarity\n",
|
| 435 |
+
"count 1600.000000 1600.000000\n",
|
| 436 |
+
"mean 0.500000 0.500000\n",
|
| 437 |
+
"std 0.500156 0.500156\n",
|
| 438 |
+
"min 0.000000 0.000000\n",
|
| 439 |
+
"25% 0.000000 0.000000\n",
|
| 440 |
+
"50% 0.500000 0.500000\n",
|
| 441 |
+
"75% 1.000000 1.000000\n",
|
| 442 |
+
"max 1.000000 1.000000"
|
| 443 |
+
]
|
| 444 |
+
},
|
| 445 |
+
"execution_count": 15,
|
| 446 |
+
"metadata": {},
|
| 447 |
+
"output_type": "execute_result"
|
| 448 |
+
}
|
| 449 |
+
],
|
| 450 |
+
"source": [
|
| 451 |
+
"df = data.sample(frac=1)\n",
|
| 452 |
+
"df.describe()"
|
| 453 |
+
]
|
| 454 |
+
},
|
| 455 |
+
{
|
| 456 |
+
"cell_type": "code",
|
| 457 |
+
"execution_count": null,
|
| 458 |
+
"metadata": {
|
| 459 |
+
"id": "gqCqI9xSriAb"
|
| 460 |
+
},
|
| 461 |
+
"outputs": [],
|
| 462 |
+
"source": [
|
| 463 |
+
"def create_class(c):\n",
|
| 464 |
+
" if c['polarity'] == 1 and c['deceptive'] == 1:\n",
|
| 465 |
+
" return [1,1]\n",
|
| 466 |
+
" elif c['polarity'] == 1 and c['deceptive'] == 0:\n",
|
| 467 |
+
" return [1,0]\n",
|
| 468 |
+
" elif c['polarity'] == 0 and c['deceptive'] == 1:\n",
|
| 469 |
+
" return [0,1]\n",
|
| 470 |
+
" else:\n",
|
| 471 |
+
" return [0,0]\n",
|
| 472 |
+
"\n",
|
| 473 |
+
"def specific_class(c):\n",
|
| 474 |
+
" if c['polarity'] == 1 and c['deceptive'] == 1: # Actually Deceptive ---> 0\n",
|
| 475 |
+
" return \"TRUE_POSITIVE\"\n",
|
| 476 |
+
" elif c['polarity'] == 1 and c['deceptive'] == 0: # Actually Not Deceptive ---> 1\n",
|
| 477 |
+
" return \"FALSE_POSITIVE\"\n",
|
| 478 |
+
" elif c['polarity'] == 0 and c['deceptive'] == 1: # Actually Not Deceptive ---> 2\n",
|
| 479 |
+
" return \"TRUE_NEGATIVE\"\n",
|
| 480 |
+
" else: # Actually Deceptive ---> 3\n",
|
| 481 |
+
" return \"FALSE_NEGATIVE\"\n",
|
| 482 |
+
"\n",
|
| 483 |
+
"data['final_class'] = data.apply(create_class, axis=1)\n",
|
| 484 |
+
"data['given_class'] = data.apply(specific_class, axis=1)"
|
| 485 |
+
]
|
| 486 |
+
},
|
| 487 |
+
{
|
| 488 |
+
"cell_type": "code",
|
| 489 |
+
"execution_count": null,
|
| 490 |
+
"metadata": {
|
| 491 |
+
"id": "0KtN7332rkOJ"
|
| 492 |
+
},
|
| 493 |
+
"outputs": [],
|
| 494 |
+
"source": [
|
| 495 |
+
"from sklearn import preprocessing\n",
|
| 496 |
+
"\n",
|
| 497 |
+
"label_encoder = preprocessing.LabelEncoder()\n",
|
| 498 |
+
"\n",
|
| 499 |
+
"data['given_class'] = label_encoder.fit_transform(data['given_class'])"
|
| 500 |
+
]
|
| 501 |
+
},
|
| 502 |
+
{
|
| 503 |
+
"cell_type": "code",
|
| 504 |
+
"execution_count": 251,
|
| 505 |
+
"metadata": {
|
| 506 |
+
"colab": {
|
| 507 |
+
"base_uri": "https://localhost:8080/"
|
| 508 |
+
},
|
| 509 |
+
"id": "MW0O6_v3EM2G",
|
| 510 |
+
"outputId": "ab5238a9-8afb-4af5-8c49-69bab79c8caa"
|
| 511 |
+
},
|
| 512 |
+
"outputs": [
|
| 513 |
+
{
|
| 514 |
+
"data": {
|
| 515 |
+
"text/plain": [
|
| 516 |
+
"0 [1, 1]\n",
|
| 517 |
+
"1 [1, 1]\n",
|
| 518 |
+
"2 [1, 1]\n",
|
| 519 |
+
"3 [1, 1]\n",
|
| 520 |
+
"4 [1, 1]\n",
|
| 521 |
+
" ... \n",
|
| 522 |
+
"1595 [0, 0]\n",
|
| 523 |
+
"1596 [0, 0]\n",
|
| 524 |
+
"1597 [0, 0]\n",
|
| 525 |
+
"1598 [0, 0]\n",
|
| 526 |
+
"1599 [0, 0]\n",
|
| 527 |
+
"Name: final_class, Length: 1600, dtype: object"
|
| 528 |
+
]
|
| 529 |
+
},
|
| 530 |
+
"execution_count": 251,
|
| 531 |
+
"metadata": {},
|
| 532 |
+
"output_type": "execute_result"
|
| 533 |
+
}
|
| 534 |
+
],
|
| 535 |
+
"source": [
|
| 536 |
+
"data['final_class']"
|
| 537 |
+
]
|
| 538 |
+
},
|
| 539 |
+
{
|
| 540 |
+
"cell_type": "code",
|
| 541 |
+
"execution_count": null,
|
| 542 |
+
"metadata": {
|
| 543 |
+
"id": "F24YJHdermPy"
|
| 544 |
+
},
|
| 545 |
+
"outputs": [],
|
| 546 |
+
"source": [
|
| 547 |
+
"Y = data['given_class']\n",
|
| 548 |
+
"encoder = LabelEncoder()\n",
|
| 549 |
+
"encoder.fit(Y)\n",
|
| 550 |
+
"encoded_Y = encoder.transform(Y)\n",
|
| 551 |
+
"dummy_y = to_categorical(encoded_Y)"
|
| 552 |
+
]
|
| 553 |
+
},
|
| 554 |
+
{
|
| 555 |
+
"cell_type": "code",
|
| 556 |
+
"execution_count": 247,
|
| 557 |
+
"metadata": {
|
| 558 |
+
"colab": {
|
| 559 |
+
"base_uri": "https://localhost:8080/"
|
| 560 |
+
},
|
| 561 |
+
"id": "wmCJ8i83D1x4",
|
| 562 |
+
"outputId": "89d49003-3a75-421d-884d-e0d032cab6ca"
|
| 563 |
+
},
|
| 564 |
+
"outputs": [
|
| 565 |
+
{
|
| 566 |
+
"data": {
|
| 567 |
+
"text/plain": [
|
| 568 |
+
"array([[0., 0., 0., 1.],\n",
|
| 569 |
+
" [0., 0., 0., 1.],\n",
|
| 570 |
+
" [0., 0., 0., 1.],\n",
|
| 571 |
+
" ...,\n",
|
| 572 |
+
" [1., 0., 0., 0.],\n",
|
| 573 |
+
" [1., 0., 0., 0.],\n",
|
| 574 |
+
" [1., 0., 0., 0.]], dtype=float32)"
|
| 575 |
+
]
|
| 576 |
+
},
|
| 577 |
+
"execution_count": 247,
|
| 578 |
+
"metadata": {},
|
| 579 |
+
"output_type": "execute_result"
|
| 580 |
+
}
|
| 581 |
+
],
|
| 582 |
+
"source": [
|
| 583 |
+
"dummy_y"
|
| 584 |
+
]
|
| 585 |
+
},
|
| 586 |
+
{
|
| 587 |
+
"cell_type": "code",
|
| 588 |
+
"execution_count": null,
|
| 589 |
+
"metadata": {
|
| 590 |
+
"id": "U0OJ5Qhbrocj"
|
| 591 |
+
},
|
| 592 |
+
"outputs": [],
|
| 593 |
+
"source": [
|
| 594 |
+
"textData = pd.DataFrame(list(data['text']))\n"
|
| 595 |
+
]
|
| 596 |
+
},
|
| 597 |
+
{
|
| 598 |
+
"cell_type": "code",
|
| 599 |
+
"execution_count": null,
|
| 600 |
+
"metadata": {
|
| 601 |
+
"id": "c_WdJiovrwpN"
|
| 602 |
+
},
|
| 603 |
+
"outputs": [],
|
| 604 |
+
"source": [
|
| 605 |
+
"stemmer = snowballstemmer.EnglishStemmer()\n",
|
| 606 |
+
"\n",
|
| 607 |
+
"stop = stopwords.words('english')\n",
|
| 608 |
+
"stop.extend(['may','also','zero','one','two','three','four','five','six','seven','eight','nine','ten','across','among','beside','however','yet','within']+list(ascii_lowercase))\n",
|
| 609 |
+
"stoplist = stemmer.stemWords(stop)\n",
|
| 610 |
+
"stoplist = set(stoplist)\n",
|
| 611 |
+
"stop = set(sorted(stop + list(stoplist)))"
|
| 612 |
+
]
|
| 613 |
+
},
|
| 614 |
+
{
|
| 615 |
+
"cell_type": "code",
|
| 616 |
+
"execution_count": null,
|
| 617 |
+
"metadata": {
|
| 618 |
+
"colab": {
|
| 619 |
+
"base_uri": "https://localhost:8080/"
|
| 620 |
+
},
|
| 621 |
+
"id": "pUJtMqjZryE9",
|
| 622 |
+
"outputId": "295b19f7-94fa-447b-b964-4017b0593401"
|
| 623 |
+
},
|
| 624 |
+
"outputs": [
|
| 625 |
+
{
|
| 626 |
+
"name": "stderr",
|
| 627 |
+
"output_type": "stream",
|
| 628 |
+
"text": [
|
| 629 |
+
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n",
|
| 630 |
+
"[nltk_data] Unzipping corpora/stopwords.zip.\n"
|
| 631 |
+
]
|
| 632 |
+
},
|
| 633 |
+
{
|
| 634 |
+
"data": {
|
| 635 |
+
"text/plain": [
|
| 636 |
+
"True"
|
| 637 |
+
]
|
| 638 |
+
},
|
| 639 |
+
"execution_count": 23,
|
| 640 |
+
"metadata": {},
|
| 641 |
+
"output_type": "execute_result"
|
| 642 |
+
}
|
| 643 |
+
],
|
| 644 |
+
"source": [
|
| 645 |
+
"nltk.download('stopwords')"
|
| 646 |
+
]
|
| 647 |
+
},
|
| 648 |
+
{
|
| 649 |
+
"cell_type": "code",
|
| 650 |
+
"execution_count": null,
|
| 651 |
+
"metadata": {
|
| 652 |
+
"id": "_FG8kbvgr9HS"
|
| 653 |
+
},
|
| 654 |
+
"outputs": [],
|
| 655 |
+
"source": [
|
| 656 |
+
"textData[0].replace('[!\"#%\\'()*+,-./:;<=>?@\\[\\]^_`{|}~1234567890’”“′‘\\\\\\]',' ',inplace=True,regex=True)\n",
|
| 657 |
+
"wordlist = filter(None, \" \".join(list(set(list(itertools.chain(*textData[0].str.split(' ')))))).split(\" \"))\n",
|
| 658 |
+
"data['stemmed_text_data'] = [' '.join(filter(None,filter(lambda word: word not in stop, line))) for line in textData[0].str.lower().str.split(' ')]"
|
| 659 |
+
]
|
| 660 |
+
},
|
| 661 |
+
{
|
| 662 |
+
"cell_type": "code",
|
| 663 |
+
"execution_count": null,
|
| 664 |
+
"metadata": {
|
| 665 |
+
"id": "fjUfTsjEsDh2"
|
| 666 |
+
},
|
| 667 |
+
"outputs": [],
|
| 668 |
+
"source": [
|
| 669 |
+
"minimum_count = 1\n",
|
| 670 |
+
"str_frequencies = pd.DataFrame(list(Counter(filter(None,list(itertools.chain(*data['stemmed_text_data'].str.split(' '))))).items()),columns=['word','count'])\n",
|
| 671 |
+
"low_frequency_words = set(str_frequencies[str_frequencies['count'] < minimum_count]['word'])\n",
|
| 672 |
+
"data['stemmed_text_data'] = [' '.join(filter(None,filter(lambda word: word not in low_frequency_words, line))) for line in data['stemmed_text_data'].str.split(' ')]\n",
|
| 673 |
+
"data['stemmed_text_data'] = [\" \".join(stemmer.stemWords(re.sub('[!\"#%\\'()*+,-./:;<=>?@\\[\\]^_`{|}~1234567890’”“′‘\\\\\\]',' ', next_text).split(' '))) for next_text in data['stemmed_text_data']]"
|
| 674 |
+
]
|
| 675 |
+
},
|
| 676 |
+
{
|
| 677 |
+
"cell_type": "code",
|
| 678 |
+
"execution_count": null,
|
| 679 |
+
"metadata": {
|
| 680 |
+
"id": "GX-Gd8M6sEpp"
|
| 681 |
+
},
|
| 682 |
+
"outputs": [],
|
| 683 |
+
"source": [
|
| 684 |
+
"lmtzr = WordNetLemmatizer()\n",
|
| 685 |
+
"w = re.compile(\"\\w+\",re.I)\n",
|
| 686 |
+
"\n",
|
| 687 |
+
"def label_sentences(df, input_point):\n",
|
| 688 |
+
" labeled_sentences = []\n",
|
| 689 |
+
" list_sen = []\n",
|
| 690 |
+
" for index, datapoint in df.iterrows():\n",
|
| 691 |
+
" tokenized_words = re.findall(w,datapoint[input_point].lower())\n",
|
| 692 |
+
" labeled_sentences.append(TaggedDocument(words=tokenized_words, tags=['SENT_%s' %index]))\n",
|
| 693 |
+
" list_sen.append(tokenized_words)\n",
|
| 694 |
+
" return labeled_sentences, list_sen\n",
|
| 695 |
+
"\n",
|
| 696 |
+
"def train_doc2vec_model(labeled_sentences):\n",
|
| 697 |
+
" model = Doc2Vec(min_count=1, window=9, vector_size=512, sample=1e-4, negative=5, workers=7)\n",
|
| 698 |
+
" model.build_vocab(labeled_sentences)\n",
|
| 699 |
+
" pretrained_weights = model.wv.vectors\n",
|
| 700 |
+
" vocab_size, embedding_size = pretrained_weights.shape\n",
|
| 701 |
+
" model.train(labeled_sentences, total_examples=vocab_size, epochs=400)\n",
|
| 702 |
+
"\n",
|
| 703 |
+
" return model"
|
| 704 |
+
]
|
| 705 |
+
},
|
| 706 |
+
{
|
| 707 |
+
"cell_type": "code",
|
| 708 |
+
"execution_count": null,
|
| 709 |
+
"metadata": {
|
| 710 |
+
"id": "2C_5s3UOsGfU"
|
| 711 |
+
},
|
| 712 |
+
"outputs": [],
|
| 713 |
+
"source": [
|
| 714 |
+
"textData = data['stemmed_text_data'].to_frame().reset_index()\n",
|
| 715 |
+
"sen, corpus = label_sentences(textData, 'stemmed_text_data')"
|
| 716 |
+
]
|
| 717 |
+
},
|
| 718 |
+
{
|
| 719 |
+
"cell_type": "code",
|
| 720 |
+
"execution_count": null,
|
| 721 |
+
"metadata": {
|
| 722 |
+
"id": "qpb3aMvW_jdj"
|
| 723 |
+
},
|
| 724 |
+
"outputs": [],
|
| 725 |
+
"source": [
|
| 726 |
+
"sen"
|
| 727 |
+
]
|
| 728 |
+
},
|
| 729 |
+
{
|
| 730 |
+
"cell_type": "code",
|
| 731 |
+
"execution_count": null,
|
| 732 |
+
"metadata": {
|
| 733 |
+
"id": "JeK3t6_HsNv9"
|
| 734 |
+
},
|
| 735 |
+
"outputs": [],
|
| 736 |
+
"source": [
|
| 737 |
+
"doc2vec_model = train_doc2vec_model(sen)"
|
| 738 |
+
]
|
| 739 |
+
},
|
| 740 |
+
{
|
| 741 |
+
"cell_type": "code",
|
| 742 |
+
"execution_count": null,
|
| 743 |
+
"metadata": {
|
| 744 |
+
"id": "DyX1XG1usQMm"
|
| 745 |
+
},
|
| 746 |
+
"outputs": [],
|
| 747 |
+
"source": [
|
| 748 |
+
"doc2vec_model.save(\"doc2vec_model_opinion_corpus.d2v\")"
|
| 749 |
+
]
|
| 750 |
+
},
|
| 751 |
+
{
|
| 752 |
+
"cell_type": "code",
|
| 753 |
+
"execution_count": null,
|
| 754 |
+
"metadata": {
|
| 755 |
+
"id": "l0OAFencszum"
|
| 756 |
+
},
|
| 757 |
+
"outputs": [],
|
| 758 |
+
"source": [
|
| 759 |
+
"doc2vec_model = Doc2Vec.load(\"doc2vec_model_opinion_corpus.d2v\")"
|
| 760 |
+
]
|
| 761 |
+
},
|
| 762 |
+
{
|
| 763 |
+
"cell_type": "code",
|
| 764 |
+
"execution_count": null,
|
| 765 |
+
"metadata": {
|
| 766 |
+
"colab": {
|
| 767 |
+
"base_uri": "https://localhost:8080/"
|
| 768 |
+
},
|
| 769 |
+
"id": "ZJTp1POIs1sQ",
|
| 770 |
+
"outputId": "5788b8b8-3f66-4d4a-e22a-6bff020adf1e"
|
| 771 |
+
},
|
| 772 |
+
"outputs": [
|
| 773 |
+
{
|
| 774 |
+
"name": "stderr",
|
| 775 |
+
"output_type": "stream",
|
| 776 |
+
"text": [
|
| 777 |
+
"/usr/local/lib/python3.10/dist-packages/sklearn/feature_extraction/text.py:528: UserWarning: The parameter 'token_pattern' will not be used since 'tokenizer' is not None'\n",
|
| 778 |
+
" warnings.warn(\n"
|
| 779 |
+
]
|
| 780 |
+
}
|
| 781 |
+
],
|
| 782 |
+
"source": [
|
| 783 |
+
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
|
| 784 |
+
"from sklearn.decomposition import TruncatedSVD\n",
|
| 785 |
+
"\n",
|
| 786 |
+
"tfidf1 = TfidfVectorizer(tokenizer=lambda i:i, lowercase=False, ngram_range=(1,1))\n",
|
| 787 |
+
"result_train1 = tfidf1.fit_transform(corpus)\n",
|
| 788 |
+
"\n",
|
| 789 |
+
"tfidf2 = TfidfVectorizer(tokenizer=lambda i:i, lowercase=False, ngram_range=(1,2))\n",
|
| 790 |
+
"result_train2 = tfidf2.fit_transform(corpus)\n",
|
| 791 |
+
"\n",
|
| 792 |
+
"tfidf3 = TfidfVectorizer(tokenizer=lambda i:i, lowercase=False, ngram_range=(1,3))\n",
|
| 793 |
+
"result_train3 = tfidf3.fit_transform(corpus)\n",
|
| 794 |
+
"\n",
|
| 795 |
+
"svd = TruncatedSVD(n_components=512, n_iter=40, random_state=34)\n",
|
| 796 |
+
"tfidf_data1 = svd.fit_transform(result_train1)\n",
|
| 797 |
+
"tfidf_data2 = svd.fit_transform(result_train2)\n",
|
| 798 |
+
"tfidf_data3 = svd.fit_transform(result_train3)"
|
| 799 |
+
]
|
| 800 |
+
},
|
| 801 |
+
{
|
| 802 |
+
"cell_type": "code",
|
| 803 |
+
"execution_count": null,
|
| 804 |
+
"metadata": {
|
| 805 |
+
"id": "io0D71F00Wv8"
|
| 806 |
+
},
|
| 807 |
+
"outputs": [],
|
| 808 |
+
"source": [
|
| 809 |
+
"nlp = spacy.load(\"en_core_web_sm\")"
|
| 810 |
+
]
|
| 811 |
+
},
|
| 812 |
+
{
|
| 813 |
+
"cell_type": "code",
|
| 814 |
+
"execution_count": null,
|
| 815 |
+
"metadata": {
|
| 816 |
+
"id": "QR6PqZREs3EA"
|
| 817 |
+
},
|
| 818 |
+
"outputs": [],
|
| 819 |
+
"source": [
|
| 820 |
+
"from sklearn.feature_extraction.text import CountVectorizer\n",
|
| 821 |
+
"import spacy\n",
|
| 822 |
+
"\n",
|
| 823 |
+
"nlp = spacy.load(\"en_core_web_sm\")\n",
|
| 824 |
+
"temp_textData = pd.DataFrame(list(data['text']))\n",
|
| 825 |
+
"\n",
|
| 826 |
+
"overall_pos_tags_tokens = []\n",
|
| 827 |
+
"overall_pos = []\n",
|
| 828 |
+
"overall_tokens = []\n",
|
| 829 |
+
"overall_dep = []\n",
|
| 830 |
+
"\n",
|
| 831 |
+
"for i in range(1600):\n",
|
| 832 |
+
" doc = nlp(temp_textData[0][i])\n",
|
| 833 |
+
" given_pos_tags_tokens = []\n",
|
| 834 |
+
" given_pos = []\n",
|
| 835 |
+
" given_tokens = []\n",
|
| 836 |
+
" given_dep = []\n",
|
| 837 |
+
" for token in doc:\n",
|
| 838 |
+
" output = \"%s_%s\" % (token.pos_, token.tag_)\n",
|
| 839 |
+
" given_pos_tags_tokens.append(output)\n",
|
| 840 |
+
" given_pos.append(token.pos_)\n",
|
| 841 |
+
" given_tokens.append(token.tag_)\n",
|
| 842 |
+
" given_dep.append(token.dep_)\n",
|
| 843 |
+
"\n",
|
| 844 |
+
" overall_pos_tags_tokens.append(given_pos_tags_tokens)\n",
|
| 845 |
+
" overall_pos.append(given_pos)\n",
|
| 846 |
+
" overall_tokens.append(given_tokens)\n",
|
| 847 |
+
" overall_dep.append(given_dep)\n"
|
| 848 |
+
]
|
| 849 |
+
},
|
| 850 |
+
{
|
| 851 |
+
"cell_type": "code",
|
| 852 |
+
"execution_count": null,
|
| 853 |
+
"metadata": {
|
| 854 |
+
"id": "O6C2OJ8KEzHk"
|
| 855 |
+
},
|
| 856 |
+
"outputs": [],
|
| 857 |
+
"source": [
|
| 858 |
+
"overall_tokens"
|
| 859 |
+
]
|
| 860 |
+
},
|
| 861 |
+
{
|
| 862 |
+
"cell_type": "code",
|
| 863 |
+
"execution_count": null,
|
| 864 |
+
"metadata": {
|
| 865 |
+
"colab": {
|
| 866 |
+
"base_uri": "https://localhost:8080/"
|
| 867 |
+
},
|
| 868 |
+
"id": "4PxkBoQgs4wV",
|
| 869 |
+
"outputId": "07f59ab7-dbc0-4b41-e712-31a165e6ddf2"
|
| 870 |
+
},
|
| 871 |
+
"outputs": [
|
| 872 |
+
{
|
| 873 |
+
"name": "stderr",
|
| 874 |
+
"output_type": "stream",
|
| 875 |
+
"text": [
|
| 876 |
+
"/usr/local/lib/python3.10/dist-packages/sklearn/feature_extraction/text.py:528: UserWarning: The parameter 'token_pattern' will not be used since 'tokenizer' is not None'\n",
|
| 877 |
+
" warnings.warn(\n"
|
| 878 |
+
]
|
| 879 |
+
}
|
| 880 |
+
],
|
| 881 |
+
"source": [
|
| 882 |
+
"import numpy as np\n",
|
| 883 |
+
"from sklearn.feature_extraction.text import CountVectorizer\n",
|
| 884 |
+
"from sklearn.preprocessing import MinMaxScaler\n",
|
| 885 |
+
"\n",
|
| 886 |
+
"count = CountVectorizer(tokenizer=lambda i: i, lowercase=False)\n",
|
| 887 |
+
"pos_tags_data = count.fit_transform(overall_pos_tags_tokens).todense()\n",
|
| 888 |
+
"pos_data = count.fit_transform(overall_pos).todense()\n",
|
| 889 |
+
"tokens_data = count.fit_transform(overall_tokens).todense()\n",
|
| 890 |
+
"dep_data = count.fit_transform(overall_dep).todense()\n",
|
| 891 |
+
"\n",
|
| 892 |
+
"min_max_scaler = MinMaxScaler()\n",
|
| 893 |
+
"\n",
|
| 894 |
+
"normalized_pos_tags_data = min_max_scaler.fit_transform(np.asarray(pos_tags_data))\n",
|
| 895 |
+
"normalized_pos_data = min_max_scaler.fit_transform(np.asarray(pos_data))\n",
|
| 896 |
+
"normalized_tokens_data = min_max_scaler.fit_transform(np.asarray(tokens_data))\n",
|
| 897 |
+
"normalized_dep_data = min_max_scaler.fit_transform(np.asarray(dep_data))\n",
|
| 898 |
+
"\n",
|
| 899 |
+
"# Convert the scaled data to numpy arrays\n",
|
| 900 |
+
"normalized_pos_tags_data = np.asarray(normalized_pos_tags_data)\n",
|
| 901 |
+
"normalized_pos_data = np.asarray(normalized_pos_data)\n",
|
| 902 |
+
"normalized_tokens_data = np.asarray(normalized_tokens_data)\n",
|
| 903 |
+
"normalized_dep_data = np.asarray(normalized_dep_data)\n",
|
| 904 |
+
"\n",
|
| 905 |
+
"final_pos_tags_data = np.zeros(shape=(1600, 512)).astype(np.float32)\n",
|
| 906 |
+
"final_pos_data = np.zeros(shape=(1600, 512)).astype(np.float32)\n",
|
| 907 |
+
"final_tokens_data = np.zeros(shape=(1600, 512)).astype(np.float32)\n",
|
| 908 |
+
"final_dep_data = np.zeros(shape=(1600, 512)).astype(np.float32)\n",
|
| 909 |
+
"\n",
|
| 910 |
+
"# Assign the converted arrays to the final arrays\n",
|
| 911 |
+
"final_pos_tags_data[:normalized_pos_tags_data.shape[0], :normalized_pos_tags_data.shape[1]] = normalized_pos_tags_data\n",
|
| 912 |
+
"final_pos_data[:normalized_pos_data.shape[0], :normalized_pos_data.shape[1]] = normalized_pos_data\n",
|
| 913 |
+
"final_tokens_data[:normalized_tokens_data.shape[0], :normalized_tokens_data.shape[1]] = normalized_tokens_data\n",
|
| 914 |
+
"final_dep_data[:normalized_dep_data.shape[0], :normalized_dep_data.shape[1]] = normalized_dep_data\n"
|
| 915 |
+
]
|
| 916 |
+
},
|
| 917 |
+
{
|
| 918 |
+
"cell_type": "code",
|
| 919 |
+
"execution_count": null,
|
| 920 |
+
"metadata": {
|
| 921 |
+
"colab": {
|
| 922 |
+
"base_uri": "https://localhost:8080/"
|
| 923 |
+
},
|
| 924 |
+
"id": "jQdeLCgas6HD",
|
| 925 |
+
"outputId": "b1079e7c-c4fa-413d-bf89-9f5dc8fe36d8"
|
| 926 |
+
},
|
| 927 |
+
"outputs": [
|
| 928 |
+
{
|
| 929 |
+
"name": "stdout",
|
| 930 |
+
"output_type": "stream",
|
| 931 |
+
"text": [
|
| 932 |
+
"370\n"
|
| 933 |
+
]
|
| 934 |
+
}
|
| 935 |
+
],
|
| 936 |
+
"source": [
|
| 937 |
+
"maxlength = []\n",
|
| 938 |
+
"for i in range(0,len(sen)):\n",
|
| 939 |
+
" maxlength.append(len(sen[i][0]))\n",
|
| 940 |
+
"\n",
|
| 941 |
+
"print(max(maxlength))"
|
| 942 |
+
]
|
| 943 |
+
},
|
| 944 |
+
{
|
| 945 |
+
"cell_type": "code",
|
| 946 |
+
"execution_count": null,
|
| 947 |
+
"metadata": {
|
| 948 |
+
"id": "X5y1kjW-s7bJ"
|
| 949 |
+
},
|
| 950 |
+
"outputs": [],
|
| 951 |
+
"source": [
|
| 952 |
+
"doc2vec_model = Doc2Vec.load(\"doc2vec_model_opinion_corpus.d2v\")\n",
|
| 953 |
+
"\n",
|
| 954 |
+
"def vectorize_comments(df,d2v_model):\n",
|
| 955 |
+
" y = []\n",
|
| 956 |
+
" comments = []\n",
|
| 957 |
+
" for i in range(0,df.shape[0]):\n",
|
| 958 |
+
" label = 'SENT_%s' %i\n",
|
| 959 |
+
" comments.append(d2v_model.docvecs[label])\n",
|
| 960 |
+
" df['vectorized_comments'] = comments\n",
|
| 961 |
+
"\n",
|
| 962 |
+
" return df\n",
|
| 963 |
+
"\n",
|
| 964 |
+
"textData = vectorize_comments(textData,doc2vec_model)\n",
|
| 965 |
+
"print (textData.head(2))"
|
| 966 |
+
]
|
| 967 |
+
},
|
| 968 |
+
{
|
| 969 |
+
"cell_type": "code",
|
| 970 |
+
"execution_count": null,
|
| 971 |
+
"metadata": {
|
| 972 |
+
"id": "SUfiSDENs8cg"
|
| 973 |
+
},
|
| 974 |
+
"outputs": [],
|
| 975 |
+
"source": [
|
| 976 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 977 |
+
"from sklearn.model_selection import cross_validate,GridSearchCV\n",
|
| 978 |
+
"\n",
|
| 979 |
+
"X_train, X_test, y_train, y_test = train_test_split(textData[\"vectorized_comments\"].T.tolist(),\n",
|
| 980 |
+
" dummy_y,\n",
|
| 981 |
+
" test_size=0.1,\n",
|
| 982 |
+
" random_state=56)"
|
| 983 |
+
]
|
| 984 |
+
},
|
| 985 |
+
{
|
| 986 |
+
"cell_type": "code",
|
| 987 |
+
"execution_count": null,
|
| 988 |
+
"metadata": {
|
| 989 |
+
"id": "1ID0T5d0s-iS"
|
| 990 |
+
},
|
| 991 |
+
"outputs": [],
|
| 992 |
+
"source": [
|
| 993 |
+
"X = np.array(textData[\"vectorized_comments\"].T.tolist()).reshape((1,1600,512))\n",
|
| 994 |
+
"y = np.array(dummy_y).reshape((1600,4))\n",
|
| 995 |
+
"X_train2 = np.array(X_train).reshape((1,1440,512))\n",
|
| 996 |
+
"y_train2 = np.array(y_train).reshape((1,1440,4))\n",
|
| 997 |
+
"X_test2 = np.array(X_test).reshape((1,160,512))\n",
|
| 998 |
+
"y_test2 = np.array(y_test).reshape((1,160,4))"
|
| 999 |
+
]
|
| 1000 |
+
},
|
| 1001 |
+
{
|
| 1002 |
+
"cell_type": "code",
|
| 1003 |
+
"execution_count": null,
|
| 1004 |
+
"metadata": {
|
| 1005 |
+
"id": "GlYOfPhGs_lR"
|
| 1006 |
+
},
|
| 1007 |
+
"outputs": [],
|
| 1008 |
+
"source": [
|
| 1009 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 1010 |
+
"Xtemp = df[\"vectorized_comments\"].T.tolist()\n",
|
| 1011 |
+
"ytemp = data['given_class']\n",
|
| 1012 |
+
"training_indices = []\n",
|
| 1013 |
+
"testing_indices = []\n",
|
| 1014 |
+
"\n",
|
| 1015 |
+
"skf = StratifiedKFold(n_splits=10)\n",
|
| 1016 |
+
"skf.get_n_splits(Xtemp, ytemp)\n",
|
| 1017 |
+
"\n",
|
| 1018 |
+
"for train_index, test_index in skf.split(Xtemp, ytemp):\n",
|
| 1019 |
+
" training_indices.append(train_index)\n",
|
| 1020 |
+
" testing_indices.append(test_index)"
|
| 1021 |
+
]
|
| 1022 |
+
},
|
| 1023 |
+
{
|
| 1024 |
+
"cell_type": "code",
|
| 1025 |
+
"execution_count": 238,
|
| 1026 |
+
"metadata": {
|
| 1027 |
+
"colab": {
|
| 1028 |
+
"base_uri": "https://localhost:8080/"
|
| 1029 |
+
},
|
| 1030 |
+
"id": "-avX-WdT_Z2P",
|
| 1031 |
+
"outputId": "a2a227a5-9ff7-4ee0-8cd0-d6b8fb157363"
|
| 1032 |
+
},
|
| 1033 |
+
"outputs": [
|
| 1034 |
+
{
|
| 1035 |
+
"data": {
|
| 1036 |
+
"text/plain": [
|
| 1037 |
+
"160"
|
| 1038 |
+
]
|
| 1039 |
+
},
|
| 1040 |
+
"execution_count": 238,
|
| 1041 |
+
"metadata": {},
|
| 1042 |
+
"output_type": "execute_result"
|
| 1043 |
+
}
|
| 1044 |
+
],
|
| 1045 |
+
"source": [
|
| 1046 |
+
"len(testing_indices[2])"
|
| 1047 |
+
]
|
| 1048 |
+
},
|
| 1049 |
+
{
|
| 1050 |
+
"cell_type": "code",
|
| 1051 |
+
"execution_count": null,
|
| 1052 |
+
"metadata": {
|
| 1053 |
+
"id": "EIVEsyLiRjn7"
|
| 1054 |
+
},
|
| 1055 |
+
"outputs": [],
|
| 1056 |
+
"source": [
|
| 1057 |
+
"training_indices"
|
| 1058 |
+
]
|
| 1059 |
+
},
|
| 1060 |
+
{
|
| 1061 |
+
"cell_type": "code",
|
| 1062 |
+
"execution_count": 211,
|
| 1063 |
+
"metadata": {
|
| 1064 |
+
"colab": {
|
| 1065 |
+
"base_uri": "https://localhost:8080/"
|
| 1066 |
+
},
|
| 1067 |
+
"id": "iPc15Lwv7-L2",
|
| 1068 |
+
"outputId": "5b5578e0-27b7-4bad-92e7-ef42dda066ed"
|
| 1069 |
+
},
|
| 1070 |
+
"outputs": [
|
| 1071 |
+
{
|
| 1072 |
+
"data": {
|
| 1073 |
+
"text/plain": [
|
| 1074 |
+
"<12x12 sparse matrix of type '<class 'numpy.float64'>'\n",
|
| 1075 |
+
"\twith 20 stored elements in Compressed Sparse Row format>"
|
| 1076 |
+
]
|
| 1077 |
+
},
|
| 1078 |
+
"execution_count": 211,
|
| 1079 |
+
"metadata": {},
|
| 1080 |
+
"output_type": "execute_result"
|
| 1081 |
+
}
|
| 1082 |
+
],
|
| 1083 |
+
"source": [
|
| 1084 |
+
"result_train1"
|
| 1085 |
+
]
|
| 1086 |
+
},
|
| 1087 |
+
{
|
| 1088 |
+
"cell_type": "code",
|
| 1089 |
+
"execution_count": 212,
|
| 1090 |
+
"metadata": {
|
| 1091 |
+
"id": "8UwiqmnhtAz6"
|
| 1092 |
+
},
|
| 1093 |
+
"outputs": [],
|
| 1094 |
+
"source": [
|
| 1095 |
+
"def extractTrainingAndTestingData(givenIndex):\n",
|
| 1096 |
+
" X_train3 = np.zeros(shape=(1440, max(maxlength)+10, 512)).astype(np.float32)\n",
|
| 1097 |
+
" Y_train3 = np.zeros(shape=(1440, 4)).astype(np.float32)\n",
|
| 1098 |
+
" X_test3 = np.zeros(shape=(160, max(maxlength)+10, 512)).astype(np.float32)\n",
|
| 1099 |
+
" Y_test3 = np.zeros(shape=(160, 4)).astype(np.float32)\n",
|
| 1100 |
+
"\n",
|
| 1101 |
+
" empty_word = np.zeros(512).astype(np.float32)\n",
|
| 1102 |
+
"\n",
|
| 1103 |
+
" count_i = 0\n",
|
| 1104 |
+
" for i in training_indices[givenIndex]:\n",
|
| 1105 |
+
" len1 = len(sen[i][0])\n",
|
| 1106 |
+
" average_vector1 = np.zeros(512).astype(np.float32)\n",
|
| 1107 |
+
" average_vector2 = np.zeros(512).astype(np.float32)\n",
|
| 1108 |
+
" average_vector3 = np.zeros(512).astype(np.float32)\n",
|
| 1109 |
+
" for j in range(max(maxlength)+10):\n",
|
| 1110 |
+
" if j < len1:\n",
|
| 1111 |
+
" X_train3[count_i,j,:] = doc2vec_model[sen[i][0][j]]\n",
|
| 1112 |
+
" average_vector1 += result_train1[i, tfidf1.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1113 |
+
" average_vector2 += result_train2[i, tfidf2.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1114 |
+
" average_vector3 += result_train3[i, tfidf3.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1115 |
+
" #elif j >= len1 and j < len1 + 379:\n",
|
| 1116 |
+
" # X_train3[count_i,j,:] = glove_data[i, j-len1, :]\n",
|
| 1117 |
+
" elif j == len1:\n",
|
| 1118 |
+
" X_train3[count_i,j,:] = tfidf_data1[i]\n",
|
| 1119 |
+
" elif j == len1 + 1:\n",
|
| 1120 |
+
" X_train3[count_i,j,:] = tfidf_data2[i]\n",
|
| 1121 |
+
" elif j == len1+2:\n",
|
| 1122 |
+
" X_train3[count_i,j,:] = tfidf_data3[i]\n",
|
| 1123 |
+
" elif j == len1+3:\n",
|
| 1124 |
+
" X_train3[count_i,j,:] = average_vector1\n",
|
| 1125 |
+
" elif j == len1+4:\n",
|
| 1126 |
+
" X_train3[count_i,j,:] = average_vector2\n",
|
| 1127 |
+
" elif j == len1+5:\n",
|
| 1128 |
+
" X_train3[count_i,j,:] = average_vector3\n",
|
| 1129 |
+
" elif j == len1+6:\n",
|
| 1130 |
+
" X_train3[count_i,j,:] = final_pos_tags_data[i]\n",
|
| 1131 |
+
" elif j == len1+7:\n",
|
| 1132 |
+
" X_train3[count_i,j,:] = final_pos_data[i]\n",
|
| 1133 |
+
" elif j == len1+8:\n",
|
| 1134 |
+
" X_train3[count_i,j,:] = final_tokens_data[i]\n",
|
| 1135 |
+
" elif j == len1+9:\n",
|
| 1136 |
+
" X_train3[count_i,j,:] = final_dep_data[i]\n",
|
| 1137 |
+
" else:\n",
|
| 1138 |
+
" X_train3[count_i,j,:] = empty_word\n",
|
| 1139 |
+
"\n",
|
| 1140 |
+
" Y_train3[count_i,:] = dummy_y[i]\n",
|
| 1141 |
+
" count_i += 1\n",
|
| 1142 |
+
"\n",
|
| 1143 |
+
"\n",
|
| 1144 |
+
" count_i = 0\n",
|
| 1145 |
+
" for i in testing_indices[givenIndex]:\n",
|
| 1146 |
+
" len1 = len(sen[i][0])\n",
|
| 1147 |
+
" average_vector1 = np.zeros(512).astype(np.float32)\n",
|
| 1148 |
+
" average_vector2 = np.zeros(512).astype(np.float32)\n",
|
| 1149 |
+
" average_vector3 = np.zeros(512).astype(np.float32)\n",
|
| 1150 |
+
" for j in range(max(maxlength)+10):\n",
|
| 1151 |
+
" if j < len1:\n",
|
| 1152 |
+
" X_test3[count_i,j,:] = doc2vec_model[sen[i][0][j]]\n",
|
| 1153 |
+
" average_vector1 += result_train1[i, tfidf1.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1154 |
+
" average_vector2 += result_train2[i, tfidf2.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1155 |
+
" average_vector3 += result_train3[i, tfidf3.vocabulary_[sen[i][0][j]]] * doc2vec_model[sen[i][0][j]]\n",
|
| 1156 |
+
" #elif j >= len1 and j < len1 + 379:\n",
|
| 1157 |
+
" # X_test3[count_i,j,:] = glove_data[i, j-len1, :]\n",
|
| 1158 |
+
" elif j == len1:\n",
|
| 1159 |
+
" X_test3[count_i,j,:] = tfidf_data1[i]\n",
|
| 1160 |
+
" elif j == len1 + 1:\n",
|
| 1161 |
+
" X_test3[count_i,j,:] = tfidf_data2[i]\n",
|
| 1162 |
+
" elif j == len1+2:\n",
|
| 1163 |
+
" X_test3[count_i,j,:] = tfidf_data3[i]\n",
|
| 1164 |
+
" elif j == len1+3:\n",
|
| 1165 |
+
" X_test3[count_i,j,:] = average_vector1\n",
|
| 1166 |
+
" elif j == len1+4:\n",
|
| 1167 |
+
" X_test3[count_i,j,:] = average_vector2\n",
|
| 1168 |
+
" elif j == len1+5:\n",
|
| 1169 |
+
" X_test3[count_i,j,:] = average_vector3\n",
|
| 1170 |
+
" elif j == len1+6:\n",
|
| 1171 |
+
" X_test3[count_i,j,:] = final_pos_tags_data[i]\n",
|
| 1172 |
+
" elif j == len1+7:\n",
|
| 1173 |
+
" X_test3[count_i,j,:] = final_pos_data[i]\n",
|
| 1174 |
+
" elif j == len1+8:\n",
|
| 1175 |
+
" X_test3[count_i,j,:] = final_tokens_data[i]\n",
|
| 1176 |
+
" elif j == len1+9:\n",
|
| 1177 |
+
" X_test3[count_i,j,:] = final_dep_data[i]\n",
|
| 1178 |
+
" else:\n",
|
| 1179 |
+
" X_test3[count_i,j,:] = empty_word\n",
|
| 1180 |
+
"\n",
|
| 1181 |
+
" Y_test3[count_i,:] = dummy_y[i]\n",
|
| 1182 |
+
" count_i += 1\n",
|
| 1183 |
+
"\n",
|
| 1184 |
+
" return X_train3, X_test3, Y_train3, Y_test3"
|
| 1185 |
+
]
|
| 1186 |
+
},
|
| 1187 |
+
{
|
| 1188 |
+
"cell_type": "code",
|
| 1189 |
+
"execution_count": null,
|
| 1190 |
+
"metadata": {
|
| 1191 |
+
"id": "_ZQ6S5IhtB_8"
|
| 1192 |
+
},
|
| 1193 |
+
"outputs": [],
|
| 1194 |
+
"source": [
|
| 1195 |
+
"model = Sequential()\n",
|
| 1196 |
+
"model.add(Conv1D(filters=128, kernel_size=9, padding='same', activation='relu', input_shape=(max(maxlength)+10,512)))\n",
|
| 1197 |
+
"model.add(Dropout(0.25))\n",
|
| 1198 |
+
"model.add(MaxPooling1D(pool_size=2))\n",
|
| 1199 |
+
"model.add(Dropout(0.25))\n",
|
| 1200 |
+
"model.add(Conv1D(filters=128, kernel_size=7, padding='same', activation='relu'))\n",
|
| 1201 |
+
"model.add(Dropout(0.25))\n",
|
| 1202 |
+
"model.add(MaxPooling1D(pool_size=2))\n",
|
| 1203 |
+
"model.add(Dropout(0.25))\n",
|
| 1204 |
+
"model.add(Conv1D(filters=128, kernel_size=5, padding='same', activation='relu'))\n",
|
| 1205 |
+
"model.add(Dropout(0.25))\n",
|
| 1206 |
+
"model.add(Bidirectional(LSTM(50, dropout=0.25, recurrent_dropout=0.2)))\n",
|
| 1207 |
+
"model.add(Dense(4, activation='softmax'))\n",
|
| 1208 |
+
"model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])\n",
|
| 1209 |
+
"print(model.summary())"
|
| 1210 |
+
]
|
| 1211 |
+
},
|
| 1212 |
+
{
|
| 1213 |
+
"cell_type": "code",
|
| 1214 |
+
"execution_count": null,
|
| 1215 |
+
"metadata": {
|
| 1216 |
+
"id": "G2XuZvBOtDMs"
|
| 1217 |
+
},
|
| 1218 |
+
"outputs": [],
|
| 1219 |
+
"source": [
|
| 1220 |
+
"from sklearn.metrics import accuracy_score\n",
|
| 1221 |
+
"from keras.callbacks import ModelCheckpoint\n",
|
| 1222 |
+
"\n",
|
| 1223 |
+
"final_accuracies = []\n",
|
| 1224 |
+
"\n",
|
| 1225 |
+
"filename = 'weights.best.from_scratch%s.hdf5' % 9\n",
|
| 1226 |
+
"checkpointer = ModelCheckpoint(filepath=filename, verbose=1, save_best_only=True)\n",
|
| 1227 |
+
"X_train3, X_test3, Y_train3, Y_test3 = extractTrainingAndTestingData(9)"
|
| 1228 |
+
]
|
| 1229 |
+
},
|
| 1230 |
+
{
|
| 1231 |
+
"cell_type": "code",
|
| 1232 |
+
"execution_count": null,
|
| 1233 |
+
"metadata": {
|
| 1234 |
+
"id": "kGGf09dktEmS"
|
| 1235 |
+
},
|
| 1236 |
+
"outputs": [],
|
| 1237 |
+
"source": [
|
| 1238 |
+
"history = model.fit(X_train3, Y_train3, epochs=15, batch_size=512, callbacks=[checkpointer], validation_data=(X_test3, Y_test3), verbose=1)"
|
| 1239 |
+
]
|
| 1240 |
+
},
|
| 1241 |
+
{
|
| 1242 |
+
"cell_type": "code",
|
| 1243 |
+
"execution_count": null,
|
| 1244 |
+
"metadata": {
|
| 1245 |
+
"id": "ug5x2h7xtGNb"
|
| 1246 |
+
},
|
| 1247 |
+
"outputs": [],
|
| 1248 |
+
"source": [
|
| 1249 |
+
"model.evaluate(X_test3, Y_test3)"
|
| 1250 |
+
]
|
| 1251 |
+
},
|
| 1252 |
+
{
|
| 1253 |
+
"cell_type": "code",
|
| 1254 |
+
"execution_count": 207,
|
| 1255 |
+
"metadata": {
|
| 1256 |
+
"id": "UVKUsrk0tHil"
|
| 1257 |
+
},
|
| 1258 |
+
"outputs": [],
|
| 1259 |
+
"source": [
|
| 1260 |
+
"import matplotlib.pyplot as plt"
|
| 1261 |
+
]
|
| 1262 |
+
},
|
| 1263 |
+
{
|
| 1264 |
+
"cell_type": "code",
|
| 1265 |
+
"execution_count": null,
|
| 1266 |
+
"metadata": {
|
| 1267 |
+
"id": "BPcCy47XtKcL"
|
| 1268 |
+
},
|
| 1269 |
+
"outputs": [],
|
| 1270 |
+
"source": [
|
| 1271 |
+
"model.load_weights(filename)"
|
| 1272 |
+
]
|
| 1273 |
+
},
|
| 1274 |
+
{
|
| 1275 |
+
"cell_type": "code",
|
| 1276 |
+
"execution_count": null,
|
| 1277 |
+
"metadata": {
|
| 1278 |
+
"id": "csp-z21UtLUT"
|
| 1279 |
+
},
|
| 1280 |
+
"outputs": [],
|
| 1281 |
+
"source": [
|
| 1282 |
+
"for i in range(10):\n",
|
| 1283 |
+
" filename = 'weights.best.from_scratch%s.hdf5' % i\n",
|
| 1284 |
+
" checkpointer = ModelCheckpoint(filepath=filename, verbose=1, save_best_only=True)\n",
|
| 1285 |
+
" X_train3, X_test3, Y_train3, Y_test3 = extractTrainingAndTestingData(i)\n",
|
| 1286 |
+
" model.fit(X_train3, Y_train3, epochs=10, batch_size=512, callbacks=[checkpointer], validation_data=(X_test3, Y_test3))\n",
|
| 1287 |
+
" model.load_weights(filename)\n",
|
| 1288 |
+
" predicted = np.rint(model.predict(X_test3))\n",
|
| 1289 |
+
" final_accuracies.append(accuracy_score(Y_test3, predicted))\n",
|
| 1290 |
+
" print(accuracy_score(Y_test3, predicted))"
|
| 1291 |
+
]
|
| 1292 |
+
},
|
| 1293 |
+
{
|
| 1294 |
+
"cell_type": "code",
|
| 1295 |
+
"execution_count": null,
|
| 1296 |
+
"metadata": {
|
| 1297 |
+
"colab": {
|
| 1298 |
+
"base_uri": "https://localhost:8080/"
|
| 1299 |
+
},
|
| 1300 |
+
"id": "aKhWVJjFLE_9",
|
| 1301 |
+
"outputId": "0a8053a8-3bae-46b1-b154-31fd2030465b"
|
| 1302 |
+
},
|
| 1303 |
+
"outputs": [
|
| 1304 |
+
{
|
| 1305 |
+
"data": {
|
| 1306 |
+
"text/plain": [
|
| 1307 |
+
"380"
|
| 1308 |
+
]
|
| 1309 |
+
},
|
| 1310 |
+
"execution_count": 162,
|
| 1311 |
+
"metadata": {},
|
| 1312 |
+
"output_type": "execute_result"
|
| 1313 |
+
}
|
| 1314 |
+
],
|
| 1315 |
+
"source": [
|
| 1316 |
+
"len(X_test3[0])"
|
| 1317 |
+
]
|
| 1318 |
+
},
|
| 1319 |
+
{
|
| 1320 |
+
"cell_type": "code",
|
| 1321 |
+
"execution_count": null,
|
| 1322 |
+
"metadata": {
|
| 1323 |
+
"colab": {
|
| 1324 |
+
"base_uri": "https://localhost:8080/"
|
| 1325 |
+
},
|
| 1326 |
+
"id": "73d3h_lhL5r8",
|
| 1327 |
+
"outputId": "8da114d8-2901-49b2-fbcd-90b821b392ad"
|
| 1328 |
+
},
|
| 1329 |
+
"outputs": [
|
| 1330 |
+
{
|
| 1331 |
+
"data": {
|
| 1332 |
+
"text/plain": [
|
| 1333 |
+
"160"
|
| 1334 |
+
]
|
| 1335 |
+
},
|
| 1336 |
+
"execution_count": 161,
|
| 1337 |
+
"metadata": {},
|
| 1338 |
+
"output_type": "execute_result"
|
| 1339 |
+
}
|
| 1340 |
+
],
|
| 1341 |
+
"source": [
|
| 1342 |
+
"len(Y_test3)"
|
| 1343 |
+
]
|
| 1344 |
+
},
|
| 1345 |
+
{
|
| 1346 |
+
"cell_type": "code",
|
| 1347 |
+
"execution_count": null,
|
| 1348 |
+
"metadata": {
|
| 1349 |
+
"colab": {
|
| 1350 |
+
"base_uri": "https://localhost:8080/"
|
| 1351 |
+
},
|
| 1352 |
+
"id": "EGeLg-HXtMlu",
|
| 1353 |
+
"outputId": "c41250cd-b6e6-4b92-a775-d010fbdc803a"
|
| 1354 |
+
},
|
| 1355 |
+
"outputs": [
|
| 1356 |
+
{
|
| 1357 |
+
"name": "stdout",
|
| 1358 |
+
"output_type": "stream",
|
| 1359 |
+
"text": [
|
| 1360 |
+
"0.8875\n"
|
| 1361 |
+
]
|
| 1362 |
+
}
|
| 1363 |
+
],
|
| 1364 |
+
"source": [
|
| 1365 |
+
"print(sum(final_accuracies) / len(final_accuracies))"
|
| 1366 |
+
]
|
| 1367 |
+
}
|
| 1368 |
+
],
|
| 1369 |
+
"metadata": {
|
| 1370 |
+
"colab": {
|
| 1371 |
+
"provenance": []
|
| 1372 |
+
},
|
| 1373 |
+
"kernelspec": {
|
| 1374 |
+
"display_name": "Python 3",
|
| 1375 |
+
"name": "python3"
|
| 1376 |
+
},
|
| 1377 |
+
"language_info": {
|
| 1378 |
+
"name": "python"
|
| 1379 |
+
}
|
| 1380 |
+
},
|
| 1381 |
+
"nbformat": 4,
|
| 1382 |
+
"nbformat_minor": 0
|
| 1383 |
+
}
|
vercel.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"rewrites": [
|
| 3 |
+
{ "source": "/(.*)", "destination": "/api/app" }
|
| 4 |
+
]
|
| 5 |
+
}
|
weights.best.from_scratch1 (1).hdf5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f84bea0167801a32295fa5321735e25b05f9b69b4c440dcdfe5f48da0db08b61
|
| 3 |
+
size 10380808
|