yitingliii commited on
Commit
edd2f0a
·
verified ·
1 Parent(s): 2c95041

Upload ml.py

Browse files
Files changed (1) hide show
  1. ml.py +63 -0
ml.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """ML.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1N6R2R3PY04PitBN4M6QNX-tuBPdqglVz
8
+ """
9
+
10
+ from google.colab import drive
11
+ drive.mount('/content/drive')
12
+
13
+ import pandas as pd
14
+
15
+ file_path = '/content/drive/My Drive/CIS 519 Final Project/Dataset/cleaned_headlines.csv'
16
+ df = pd.read_csv(file_path)
17
+ df
18
+
19
+ class_counts = df['outlet'].value_counts()
20
+ print(class_counts)
21
+
22
+ from sklearn.model_selection import train_test_split
23
+ X = df['title']
24
+ y = df['labels']
25
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
26
+
27
+ from sklearn.feature_extraction.text import TfidfVectorizer
28
+ tfidf = TfidfVectorizer(max_features=5000, ngram_range=(1, 2), stop_words='english')
29
+ X_train_tfidf = tfidf.fit_transform(X_train)
30
+ X_test_tfidf = tfidf.transform(X_test)
31
+
32
+ """# Logistic Regression"""
33
+
34
+ from sklearn.linear_model import LogisticRegression
35
+ from sklearn.metrics import accuracy_score, classification_report
36
+ model = LogisticRegression(max_iter=200)
37
+ model.fit(X_train_tfidf, y_train)
38
+ y_pred = model.predict(X_test_tfidf)
39
+ accuracy = accuracy_score(y_test, y_pred)
40
+ print(f"Logistic Regression Accuracy: {accuracy:.4f}")
41
+ print(classification_report(y_test, y_pred))
42
+
43
+ """# Random Forest"""
44
+
45
+ from sklearn.ensemble import RandomForestClassifier
46
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
47
+
48
+ model.fit(X_train_tfidf, y_train)
49
+ y_pred = model.predict(X_test_tfidf)
50
+ accuracy = accuracy_score(y_test, y_pred)
51
+ print(f"Random Forest Accuracy: {accuracy:.4f}")
52
+ print(classification_report(y_test, y_pred))
53
+
54
+ """# Support Vector Machine"""
55
+
56
+ from sklearn.svm import SVC
57
+ svm_model = SVC(kernel='linear', random_state=42)
58
+ svm_model.fit(X_train_tfidf, y_train)
59
+ y_pred = svm_model.predict(X_test_tfidf)
60
+ accuracy = accuracy_score(y_test, y_pred)
61
+ print(f"Random Forest Accuracy: {accuracy:.4f}")
62
+ print(classification_report(y_test, y_pred))
63
+