Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
1 |
from sklearn.metrics import confusion_matrix
|
2 |
from transformers import pipeline
|
3 |
import numpy as np
|
@@ -19,31 +22,68 @@ import gradio as gr
|
|
19 |
# pip install --upgrade transformers// update it if you get error
|
20 |
# !pip install gradio // download it
|
21 |
# Fetch the 20 newsgroups dataset
|
22 |
-
import warnings
|
23 |
-
warnings.filterwarnings('ignore')
|
24 |
-
warnings.simplefilter('ignore')
|
25 |
-
data = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))
|
26 |
|
|
|
|
|
|
|
27 |
# Display information about the dataset
|
28 |
print("Number of samples:", len(data.data))
|
29 |
-
print("
|
30 |
# Split the dataset into training and testing sets
|
31 |
-
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
# Define a list of classifiers to try
|
34 |
classifiers = [
|
35 |
-
|
36 |
RandomForestClassifier(),
|
37 |
SVC(),
|
38 |
LogisticRegression()
|
39 |
]
|
40 |
-
|
|
|
|
|
|
|
41 |
for classifier in classifiers:
|
42 |
# Create a pipeline with TF-IDF vectorizer and the current classifier
|
43 |
model = make_pipeline(TfidfVectorizer(), classifier)
|
44 |
|
45 |
# Train the model
|
46 |
-
model.fit(
|
47 |
|
48 |
# Make predictions on the test set
|
49 |
predictions = model.predict(X_test)
|
@@ -51,6 +91,8 @@ for classifier in classifiers:
|
|
51 |
# Evaluate the performance of the model
|
52 |
accuracy = accuracy_score(y_test, predictions)
|
53 |
print(f"\nClassifier: {classifier.__class__.__name__}")
|
|
|
|
|
54 |
print(f"Accuracy: {accuracy:.2f}")
|
55 |
|
56 |
# Display classification report
|
@@ -64,13 +106,38 @@ for classifier in classifiers:
|
|
64 |
plt.ylabel('Actual')
|
65 |
plt.title(f'Confusion Matrix - {classifier.__class__.__name__}')
|
66 |
plt.show()
|
|
|
|
|
|
|
|
|
67 |
print("\n\n\n")
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
return train.target_names[pred[0]]
|
75 |
iface=gr.Interface(fn=predict_category,inputs=gr.Textbox(lines=10, placeholder="Enter text here"),outputs="text", title="Text Classification",description="getting... the categories of Artical/news")
|
76 |
iface.launch(inline=False,share=True)
|
|
|
1 |
+
import warnings
|
2 |
+
warnings.filterwarnings('ignore')
|
3 |
+
warnings.simplefilter('ignore')
|
4 |
from sklearn.metrics import confusion_matrix
|
5 |
from transformers import pipeline
|
6 |
import numpy as np
|
|
|
22 |
# pip install --upgrade transformers// update it if you get error
|
23 |
# !pip install gradio // download it
|
24 |
# Fetch the 20 newsgroups dataset
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
data = fetch_20newsgroups(subset='all',remove=('headers', 'footers', 'quotes'))
|
27 |
+
print("First few rows of the dataset:")
|
28 |
+
print(data.data[:2])
|
29 |
# Display information about the dataset
|
30 |
print("Number of samples:", len(data.data))
|
31 |
+
print("\nTarget names:", data.target_names)
|
32 |
# Split the dataset into training and testing sets
|
33 |
+
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.1, random_state=1)
|
34 |
+
categories = ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc','comp.sys.ibm.pc.hardware','comp.sys.mac.hardware', 'comp.windows.x','misc.forsale', 'rec.autos', 'rec.motorcycles','rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt' ,'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns','talk.politics.mideast', 'talk.politics.misc','talk.religion.misc']
|
35 |
+
# Training the data on these categories
|
36 |
+
train = fetch_20newsgroups (subset='train', categories=categories)
|
37 |
+
#MultinomialNaiveBayes functon
|
38 |
+
class MultinomialNaiveBayes:
|
39 |
+
def __init__(self, alpha=0.01):
|
40 |
+
self.alpha = alpha
|
41 |
+
self.class_probs = None
|
42 |
+
self.feature_probs = None
|
43 |
+
|
44 |
+
def fit(self, X, y):
|
45 |
+
num_classes = len(np.unique(y))
|
46 |
+
num_features = X.shape[1]
|
47 |
+
|
48 |
+
# Calculate class probabilities
|
49 |
+
self.class_probs = np.zeros(num_classes)
|
50 |
+
for i in range(num_classes):
|
51 |
+
self.class_probs[i] = np.sum(y == i) / len(y)
|
52 |
+
|
53 |
+
# Calculate feature probabilities
|
54 |
+
self.feature_probs = np.zeros((num_classes, num_features))
|
55 |
+
for i in range(num_classes):
|
56 |
+
class_count = np.sum(y == i)
|
57 |
+
self.feature_probs[i, :] = (np.sum(X[y == i], axis=0) + self.alpha) / (class_count + self.alpha * num_features)
|
58 |
+
|
59 |
+
def predict(self, X):
|
60 |
+
num_samples = X.shape[0]
|
61 |
+
num_classes = len(self.class_probs)
|
62 |
+
predictions = np.zeros(num_samples, dtype=int)
|
63 |
|
64 |
+
for i in range(num_samples):
|
65 |
+
# Ensure X[i] is a 2D array with a single row
|
66 |
+
sample_probs = np.sum(np.log(self.feature_probs) * X[i, :].toarray(), axis=1) + np.log(self.class_probs)
|
67 |
+
predictions[i] = np.argmax(sample_probs)
|
68 |
+
|
69 |
+
return predictions
|
70 |
# Define a list of classifiers to try
|
71 |
classifiers = [
|
72 |
+
MultinomialNaiveBayes(alpha=.01),
|
73 |
RandomForestClassifier(),
|
74 |
SVC(),
|
75 |
LogisticRegression()
|
76 |
]
|
77 |
+
ma=0
|
78 |
+
bar_values=[]
|
79 |
+
bar_class=["MultinomialNB","RandomForestClassifier","SVC","LogisticRegression",]
|
80 |
+
classifi=None
|
81 |
for classifier in classifiers:
|
82 |
# Create a pipeline with TF-IDF vectorizer and the current classifier
|
83 |
model = make_pipeline(TfidfVectorizer(), classifier)
|
84 |
|
85 |
# Train the model
|
86 |
+
model.fit(train.data, train.target)
|
87 |
|
88 |
# Make predictions on the test set
|
89 |
predictions = model.predict(X_test)
|
|
|
91 |
# Evaluate the performance of the model
|
92 |
accuracy = accuracy_score(y_test, predictions)
|
93 |
print(f"\nClassifier: {classifier.__class__.__name__}")
|
94 |
+
maxx=round(accuracy, 2)
|
95 |
+
bar_values.append(maxx)
|
96 |
print(f"Accuracy: {accuracy:.2f}")
|
97 |
|
98 |
# Display classification report
|
|
|
106 |
plt.ylabel('Actual')
|
107 |
plt.title(f'Confusion Matrix - {classifier.__class__.__name__}')
|
108 |
plt.show()
|
109 |
+
#getting best model train
|
110 |
+
if(maxx>ma):
|
111 |
+
ma=maxx
|
112 |
+
classifi=classifier
|
113 |
print("\n\n\n")
|
114 |
+
plt.xlabel('Model', fontweight ='bold', fontsize = 15)
|
115 |
+
plt.ylabel('Accuracy', fontweight ='bold', fontsize = 15)
|
116 |
+
plt.bar(bar_class,bar_values, width = 0.4)
|
117 |
+
# Annotating each bar with its value
|
118 |
+
for i, value in enumerate(bar_values):
|
119 |
+
plt.text(i, value, f'{value:.2f}', ha='center', va='bottom', fontweight='bold')
|
120 |
+
# best algo model is trained aagain
|
121 |
+
print(f"Best accuracy model is {classifi}")
|
122 |
+
model = make_pipeline(TfidfVectorizer(), classifi)
|
123 |
+
|
124 |
+
# Train the model
|
125 |
+
model.fit(train.data, train.target)
|
126 |
+
|
127 |
+
# Make predictions on the test set
|
128 |
+
predictions = model.predict(X_test)
|
129 |
+
|
130 |
+
# Evaluate the performance of the model
|
131 |
+
accuracy = accuracy_score(y_test, predictions)
|
132 |
+
print(f"\nClassifier: {classifi}")
|
133 |
+
maxx=round(accuracy, 2)
|
134 |
+
print(f"Accuracy: {accuracy:.2f}")
|
135 |
+
|
136 |
+
# Display classification report
|
137 |
+
print("Classification Report:\n", classification_report(y_test, predictions))
|
138 |
+
conf_matrix = confusion_matrix(y_test, predictions)
|
139 |
+
def predict_category(Enter_article, train=train, model=model):
|
140 |
+
pred=model.predict([Enter_article])
|
141 |
return train.target_names[pred[0]]
|
142 |
iface=gr.Interface(fn=predict_category,inputs=gr.Textbox(lines=10, placeholder="Enter text here"),outputs="text", title="Text Classification",description="getting... the categories of Artical/news")
|
143 |
iface.launch(inline=False,share=True)
|