-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsentiment_LR.py
More file actions
215 lines (171 loc) · 5.67 KB
/
Copy pathsentiment_LR.py
File metadata and controls
215 lines (171 loc) · 5.67 KB
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, when
from pyspark.ml import Pipeline
from pyspark.ml.feature import (
RegexTokenizer, StopWordsRemover,
HashingTF, IDF, NGram, VectorAssembler
)
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark import StorageLevel
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.sql.functions import col
# ============================================================
# CONFIGURATION
# ============================================================
INPUT_PATH = "hdfs://localhost:9000/tweetanalysis/processed/cleaned_tweets"
MODEL_PATH = "hdfs://localhost:9000/tweetanalysis/models/sentiment_lr"
# ============================================================
# SPARK SESSION
# ============================================================
def create_spark_session():
spark = (
SparkSession.builder
.appName("Sentiment_LR_Optimized")
.master("spark://localhost:7077")
.config("spark.sql.shuffle.partitions", "8")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
return spark
# ============================================================
# DATA LOADING & LABELING
# ============================================================
def load_and_label_data(spark):
df = spark.read.parquet(INPUT_PATH)
df = df.withColumn(
"label",
when(col("sentiment") == 4, 1.0).otherwise(0.0)
)
df.persist(StorageLevel.MEMORY_AND_DISK)
return df
# ============================================================
# FEATURE PIPELINE
# ============================================================
def build_feature_pipeline():
tokenizer = RegexTokenizer(
inputCol="cleaned_text",
outputCol="words",
pattern="\\W+"
)
stopwords = StopWordsRemover(
inputCol="words",
outputCol="filtered_words"
)
tf = HashingTF(
inputCol="filtered_words",
outputCol="tf_features",
numFeatures=8000
)
idf = IDF(
inputCol="tf_features",
outputCol="tfidf_features",
minDocFreq=5
)
bigram = NGram(
n=2,
inputCol="filtered_words",
outputCol="bigrams"
)
bigram_tf = HashingTF(
inputCol="bigrams",
outputCol="bigram_features",
numFeatures=8000
)
assembler = VectorAssembler(
inputCols=["tfidf_features", "bigram_features"],
outputCol="features"
)
return [
tokenizer,
stopwords,
tf,
idf,
bigram,
bigram_tf,
assembler
]
# ============================================================
# MODEL
# ============================================================
def build_model():
return LogisticRegression(
featuresCol="features",
labelCol="label",
family="binomial",
maxIter=30,
regParam=0.001
)
# ============================================================
# TRAINING
# ============================================================
def train_model(df):
train_df, test_df = df.randomSplit([0.8, 0.2], seed=42)
stages = build_feature_pipeline()
stages.append(build_model())
pipeline = Pipeline(stages=stages)
model = pipeline.fit(train_df)
return model, test_df
# ============================================================
# EVALUATION & RESULT PRINTING
# ============================================================
def evaluate_model(model, test_df):
predictions = model.transform(test_df)
print("\n" + "=" * 60)
print("SENTIMENT MODEL EVALUATION RESULTS")
print("=" * 60)
metrics = {
"Accuracy": "accuracy",
"Precision": "weightedPrecision",
"Recall": "weightedRecall",
"F1-Score": "f1"
}
for name, metric in metrics.items():
evaluator = MulticlassClassificationEvaluator(
labelCol="label",
predictionCol="prediction",
metricName=metric
)
score = evaluator.evaluate(predictions)
print(f"{name:<15}: {score:.4f}")
print("=" * 60)
# --------------------------------------------------------
# Confusion Matrix
# --------------------------------------------------------
print("\nCONFUSION MATRIX (label vs prediction)")
predictions.groupBy("label", "prediction").count().orderBy("label", "prediction").show()
# --------------------------------------------------------
# Prediction Distribution
# --------------------------------------------------------
print("PREDICTION DISTRIBUTION")
predictions.groupBy("prediction").count().show()
# --------------------------------------------------------
# Sample Predictions
# --------------------------------------------------------
print("SAMPLE PREDICTIONS")
predictions.select(
col("cleaned_text"),
col("label"),
col("prediction")
).show(10, truncate=60)
return predictions
# ============================================================
# SAVE MODEL
# ============================================================
def save_model(model):
model.write().overwrite().save(MODEL_PATH)
print(f"Model saved to: {MODEL_PATH}")
# ============================================================
# MAIN
# ============================================================
def main():
spark = create_spark_session()
try:
df = load_and_label_data(spark)
model, test_df = train_model(df)
evaluate_model(model, test_df)
save_model(model)
finally:
spark.stop()
if __name__ == "__main__":
main()