-
Notifications
You must be signed in to change notification settings - Fork 0
/
CNN.py
149 lines (115 loc) · 3.96 KB
/
CNN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# Convolutional Neural Network w/Snowflake Source POC #
# Snowflake
import snowflake.connector
# Keras
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers.core import Activation, Dropout, Dense
from keras.layers import Flatten
from keras.layers import GlobalMaxPooling1D
from keras.layers.embeddings import Embedding
from keras.preprocessing.text import Tokenizer
from keras import layers
# Other
import os
import nltk
import pandas as pd
import numpy as np
import re
from nltk.corpus import stopwords
from numpy import array
import matplotlib.pyplot as plt
# sklearn
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
# Functions #
def plot_history(history):
acc = history.history["acc"]
val_acc = history.history["val_acc"]
loss = history.history["loss"]
val_loss = history.history["val_loss"]
x = range(1, len(acc) + 1)
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(x, acc, "b", label="Training acc")
plt.plot(x, val_acc, "r", label="Validation acc")
plt.title("Training and validation accuracy")
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(x, loss, "b", label="Training loss")
plt.plot(x, val_loss, "r", label="Validation loss")
plt.title("Training and validation loss")
plt.legend()
# Snowflake Credentials from env variables #
PASSWORD = os.getenv("SNOWSQL_PWD")
WAREHOUSE = os.getenv("SNOWWAREHOUSE")
ACCOUNT = os.getenv("SNOWACCT")
USER = os.getenv("SNOWUSER")
# Connection Manager for Snowflake Instance #
con = snowflake.connector.connect(
user=USER,
password=PASSWORD,
account=ACCOUNT,
warehouse=WAREHOUSE,
schema="PUBLIC",
database="CNNPOC",
)
cur = con.cursor()
sql = "SELECT * FROM CNNPOC.PUBLIC.LABELLEDREVIEWSNEW"
cur.execute(sql)
df = cur.fetch_pandas_all()
#### Start of Models ####
# Yelp Log Reg for baseline test #
df_yelp = df[df["RECORDSOURCE"] == "yelp"]
sentences = df_yelp["SENTENCE"].values
y = df_yelp["LABEL"].values
sentences_train, sentences_test, y_train, y_test = train_test_split(
sentences, y, test_size=0.25, random_state=1000
)
vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)
classifier = LogisticRegression()
classifier.fit(X_train, y_train)
score = classifier.score(X_test, y_test)
print("Accuracy of Log Reg: ", score)
# Log Reg for each unique source in dataframe #
for source in df["RECORDSOURCE"].unique():
df_source = df[df["RECORDSOURCE"] == source]
sentences = df_source["SENTENCE"].values
y = df_source["LABEL"].values
sentences_train, sentences_test, y_train, y_test = train_test_split(
sentences, y, test_size=0.25, random_state=1000
)
vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)
classifier = LogisticRegression()
classifier.fit(X_train, y_train)
score = classifier.score(X_test, y_test)
print("Accuracy for {} data: {:.4f}".format(source, score))
# Start of Convolutional Neural Net #
input_dim = X_train.shape[1]
model = Sequential()
model.add(layers.Dense(10, input_dim=input_dim, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
model.summary()
history = model.fit(
X_train,
y_train,
epochs=100,
verbose=False,
validation_data=(X_test, y_test),
batch_size=10,
)
loss, accuracy = model.evaluate(X_train, y_train, verbose=False)
print("Training Accuracy: {:.4f}".format(accuracy))
loss, accuracy = model.evaluate(X_test, y_test, verbose=False)
print("Testing Accuracy: {:.4f}".format(accuracy))
plt.style.use("ggplot")
plot_history(history)