libz 0.2__tar.gz → 0.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {libz-0.2 → libz-0.4}/PKG-INFO +1 -1
- libz-0.4/libz/DL/__init__.py +15 -0
- libz-0.4/libz/DL/prac1.py +127 -0
- libz-0.4/libz/DL/prac2.py +149 -0
- libz-0.4/libz/DL/prac3.py +252 -0
- libz-0.4/libz/DL/prac4.py +379 -0
- libz-0.4/libz/DL/prac5.py +380 -0
- libz-0.4/libz/DL/prac6.py +395 -0
- libz-0.4/libz/DL/prac7.py +144 -0
- libz-0.4/libz/DL/prac8.py +114 -0
- libz-0.4/libz/DL/prac9.py +158 -0
- libz-0.4/libz/DLG/__init__.py +15 -0
- libz-0.4/libz/DLG/prac1.py +71 -0
- libz-0.4/libz/DLG/prac2.py +108 -0
- libz-0.4/libz/DLG/prac3.py +108 -0
- libz-0.4/libz/DLG/prac4.py +105 -0
- libz-0.4/libz/DLG/prac5.py +99 -0
- libz-0.4/libz/DLG/prac6.py +119 -0
- libz-0.4/libz/DLG/prac7.py +110 -0
- libz-0.4/libz/DLG/prac8.py +141 -0
- libz-0.4/libz/DLG/prac9.py +93 -0
- libz-0.4/libz/__init__.py +5 -0
- {libz-0.2 → libz-0.4}/libz/_core.py +43 -34
- {libz-0.2 → libz-0.4}/libz.egg-info/PKG-INFO +1 -1
- {libz-0.2 → libz-0.4}/libz.egg-info/SOURCES.txt +11 -2
- {libz-0.2 → libz-0.4}/pyproject.toml +1 -1
- libz-0.2/libz/DL/__init__.py +0 -3
- libz-0.2/libz/DL/prac1.py +0 -36
- libz-0.2/libz/DL/prac10.py +0 -4
- libz-0.2/libz/DL/prac2.py +0 -4
- libz-0.2/libz/DL/prac3.py +0 -4
- libz-0.2/libz/DL/prac4.py +0 -4
- libz-0.2/libz/DL/prac5.py +0 -4
- libz-0.2/libz/DL/prac6.py +0 -4
- libz-0.2/libz/DL/prac7.py +0 -4
- libz-0.2/libz/DL/prac8.py +0 -4
- libz-0.2/libz/DL/prac9.py +0 -4
- libz-0.2/libz/__init__.py +0 -5
- {libz-0.2 → libz-0.4}/README.md +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/__init__.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac1.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac10.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac2.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac3.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac4.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac5.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac6.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac7.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac8.py +0 -0
- {libz-0.2 → libz-0.4}/libz/AWT/prac9.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/__init__.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac1.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac10.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac2.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac3.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac4.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac5.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac6.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac7.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac8.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BDA/prac9.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/__init__.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac1.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac10.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac2.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac3.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac4.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac5.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac6.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac7.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac8.py +0 -0
- {libz-0.2 → libz-0.4}/libz/BIO/prac9.py +0 -0
- {libz-0.2 → libz-0.4}/libz.egg-info/dependency_links.txt +0 -0
- {libz-0.2 → libz-0.4}/libz.egg-info/top_level.txt +0 -0
- {libz-0.2 → libz-0.4}/setup.cfg +0 -0
{libz-0.2 → libz-0.4}/PKG-INFO
RENAMED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from libz._core import register
|
|
2
|
+
|
|
3
|
+
TITLES = {
|
|
4
|
+
1: "Deep feed forward",
|
|
5
|
+
2: "Regularization and optimization",
|
|
6
|
+
3: "Semi-supervised learning",
|
|
7
|
+
4: "Multitasking",
|
|
8
|
+
5: "CNN-based handwriting recognition",
|
|
9
|
+
6: "CNN - unsupervised feature learning",
|
|
10
|
+
7: "Recurrent neural network",
|
|
11
|
+
8: "Recursive neural network (tree)",
|
|
12
|
+
9: "PCA vs linear autoencoder",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
register(__name__, globals(), TITLES)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
|
|
2
|
+
# 1. Import Libraries
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from sklearn.model_selection import train_test_split
|
|
6
|
+
from sklearn.preprocessing import StandardScaler
|
|
7
|
+
from sklearn.metrics import classification_report, confusion_matrix
|
|
8
|
+
from tensorflow.keras.models import Sequential
|
|
9
|
+
from tensorflow.keras.layers import Dense, Dropout
|
|
10
|
+
from tensorflow.keras.callbacks import EarlyStopping
|
|
11
|
+
|
|
12
|
+
# 2. Load Dataset
|
|
13
|
+
df = pd.read_csv("/content/Depression Student Dataset.csv")
|
|
14
|
+
|
|
15
|
+
# 3. Data Preprocessing
|
|
16
|
+
# Remove unnamed columns
|
|
17
|
+
df = df.loc[:, ~df.columns.str.contains("^Unnamed")]
|
|
18
|
+
|
|
19
|
+
# Drop ID column if it exists
|
|
20
|
+
df.drop(columns=["id"], inplace=True, errors="ignore")
|
|
21
|
+
|
|
22
|
+
# Handle missing values
|
|
23
|
+
for col in df.columns:
|
|
24
|
+
if df[col].isnull().any():
|
|
25
|
+
if pd.api.types.is_numeric_dtype(df[col]):
|
|
26
|
+
df[col] = df[col].fillna(df[col].median())
|
|
27
|
+
else:
|
|
28
|
+
df[col] = df[col].fillna(df[col].mode()[0])
|
|
29
|
+
|
|
30
|
+
# Encode target variable
|
|
31
|
+
df["Depression"] = df["Depression"].map({
|
|
32
|
+
"No": 0,
|
|
33
|
+
"Yes": 1
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
# Encode categorical input features
|
|
37
|
+
X = pd.get_dummies(
|
|
38
|
+
df.drop("Depression", axis=1),
|
|
39
|
+
drop_first=True,
|
|
40
|
+
dtype=int
|
|
41
|
+
)
|
|
42
|
+
y = df["Depression"]
|
|
43
|
+
|
|
44
|
+
# 4. Train-Test Split
|
|
45
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
46
|
+
X,
|
|
47
|
+
y,
|
|
48
|
+
test_size=0.20,
|
|
49
|
+
random_state=42,
|
|
50
|
+
stratify=y
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# 5. Feature Scaling
|
|
54
|
+
scaler = StandardScaler()
|
|
55
|
+
X_train = scaler.fit_transform(X_train)
|
|
56
|
+
X_test = scaler.transform(X_test)
|
|
57
|
+
|
|
58
|
+
# 6. Build Feedforward Neural Network
|
|
59
|
+
model = Sequential([
|
|
60
|
+
Dense(
|
|
61
|
+
128,
|
|
62
|
+
activation="relu",
|
|
63
|
+
input_shape=(X_train.shape[1],)
|
|
64
|
+
),
|
|
65
|
+
Dropout(0.30),
|
|
66
|
+
Dense(64, activation="relu"),
|
|
67
|
+
Dropout(0.20),
|
|
68
|
+
Dense(32, activation="relu"),
|
|
69
|
+
Dense(1, activation="sigmoid")
|
|
70
|
+
])
|
|
71
|
+
|
|
72
|
+
# 7. Compile Model
|
|
73
|
+
model.compile(
|
|
74
|
+
optimizer="adam",
|
|
75
|
+
loss="binary_crossentropy",
|
|
76
|
+
metrics=["accuracy"]
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# 8. Early Stopping
|
|
80
|
+
early_stop = EarlyStopping(
|
|
81
|
+
monitor="val_loss",
|
|
82
|
+
patience=5,
|
|
83
|
+
restore_best_weights=True
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# 9. Train Model
|
|
87
|
+
history = model.fit(
|
|
88
|
+
X_train,
|
|
89
|
+
y_train,
|
|
90
|
+
epochs=50,
|
|
91
|
+
batch_size=32,
|
|
92
|
+
validation_split=0.20,
|
|
93
|
+
callbacks=[early_stop],
|
|
94
|
+
verbose=1
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# 10. Evaluate Model
|
|
99
|
+
test_loss, test_accuracy = model.evaluate(
|
|
100
|
+
X_test,
|
|
101
|
+
y_test,
|
|
102
|
+
verbose=0
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Predict probabilities and classes
|
|
106
|
+
y_pred_prob = model.predict(X_test, verbose=0)
|
|
107
|
+
y_pred = (
|
|
108
|
+
y_pred_prob >= 0.5
|
|
109
|
+
).astype(int).ravel()
|
|
110
|
+
|
|
111
|
+
# 11. Display Results
|
|
112
|
+
# Calculate training accuracy
|
|
113
|
+
train_accuracy = model.evaluate(
|
|
114
|
+
X_train,
|
|
115
|
+
y_train,
|
|
116
|
+
verbose=0
|
|
117
|
+
)[1]
|
|
118
|
+
print(f"Training Accuracy: {train_accuracy * 100:.2f}%")
|
|
119
|
+
print(f"Testing Accuracy: {test_accuracy * 100:.2f}%")
|
|
120
|
+
|
|
121
|
+
# Classification Report
|
|
122
|
+
print("\nClassification Report:")
|
|
123
|
+
print(classification_report(y_test, y_pred))
|
|
124
|
+
|
|
125
|
+
# Confusion Matrix
|
|
126
|
+
print("Confusion Matrix:")
|
|
127
|
+
print(confusion_matrix(y_test, y_pred))
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# 1. Import Libraries
|
|
2
|
+
import warnings
|
|
3
|
+
warnings.filterwarnings("ignore")
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import seaborn as sns
|
|
9
|
+
import tensorflow as tf
|
|
10
|
+
|
|
11
|
+
from sklearn.model_selection import train_test_split
|
|
12
|
+
from sklearn.preprocessing import LabelEncoder, StandardScaler, OneHotEncoder
|
|
13
|
+
from sklearn.impute import SimpleImputer
|
|
14
|
+
from sklearn.compose import ColumnTransformer
|
|
15
|
+
from sklearn.pipeline import Pipeline
|
|
16
|
+
from sklearn.metrics import (
|
|
17
|
+
accuracy_score,
|
|
18
|
+
classification_report,
|
|
19
|
+
confusion_matrix
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from tensorflow.keras.models import Sequential
|
|
23
|
+
from tensorflow.keras.layers import Input, Dense, Dropout
|
|
24
|
+
from tensorflow.keras.optimizers import Adam
|
|
25
|
+
from tensorflow.keras.regularizers import l2
|
|
26
|
+
from tensorflow.keras.callbacks import EarlyStopping
|
|
27
|
+
|
|
28
|
+
# 2. Import SMOTE (Optional)
|
|
29
|
+
try:
|
|
30
|
+
from imblearn.over_sampling import SMOTE
|
|
31
|
+
SMOTE_AVAILABLE = True
|
|
32
|
+
except ImportError:
|
|
33
|
+
SMOTE_AVAILABLE = False
|
|
34
|
+
|
|
35
|
+
# 3. Load Dataset
|
|
36
|
+
file_path = input(
|
|
37
|
+
"Enter CSV file path (example: dataset.csv): "
|
|
38
|
+
).strip().strip('"')
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
df = pd.read_csv(file_path)
|
|
42
|
+
except Exception as error:
|
|
43
|
+
raise SystemExit(f"Could not read CSV: {error}")
|
|
44
|
+
|
|
45
|
+
# 4. Initial Data Cleaning
|
|
46
|
+
df.columns = [str(col).strip() for col in df.columns]
|
|
47
|
+
|
|
48
|
+
# Remove completely empty rows and columns
|
|
49
|
+
df = df.dropna(axis=0, how="all")
|
|
50
|
+
df = df.dropna(axis=1, how="all")
|
|
51
|
+
|
|
52
|
+
# Remove duplicate rows
|
|
53
|
+
df = df.drop_duplicates().reset_index(drop=True)
|
|
54
|
+
if df.empty:
|
|
55
|
+
raise SystemExit("Dataset is empty.")
|
|
56
|
+
|
|
57
|
+
# 5. Display Dataset Information
|
|
58
|
+
print("\nDataset shape:", df.shape)
|
|
59
|
+
print("\nColumns:")
|
|
60
|
+
for col in df.columns:
|
|
61
|
+
print(" -", col)
|
|
62
|
+
print("\nMissing values:\n", df.isnull().sum())
|
|
63
|
+
|
|
64
|
+
# 6. Select Target Column
|
|
65
|
+
target_col = input(
|
|
66
|
+
"\nEnter the target/output column to predict: "
|
|
67
|
+
).strip()
|
|
68
|
+
|
|
69
|
+
if target_col not in df.columns:
|
|
70
|
+
raise SystemExit(
|
|
71
|
+
f"Target column '{target_col}' was not found."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# 7. Clean Target Column
|
|
75
|
+
df = df.dropna(subset=[target_col])
|
|
76
|
+
df = df.drop_duplicates().copy()
|
|
77
|
+
|
|
78
|
+
if df[target_col].nunique() < 2:
|
|
79
|
+
raise SystemExit(
|
|
80
|
+
"Target must contain at least two classes."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# 8. Clean String Values
|
|
84
|
+
for col in df.select_dtypes(
|
|
85
|
+
include=["object", "string"]
|
|
86
|
+
).columns:
|
|
87
|
+
df[col] = df[col].map(
|
|
88
|
+
lambda value: value.strip()
|
|
89
|
+
if isinstance(value, str)
|
|
90
|
+
else value
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# 9. Display Target Distribution
|
|
94
|
+
print("\nTarget distribution:\n")
|
|
95
|
+
print(df[target_col].value_counts())
|
|
96
|
+
plt.figure(figsize=(8, 4))
|
|
97
|
+
df[target_col].astype(str).value_counts().plot(
|
|
98
|
+
kind="bar"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
plt.title(f"Class Distribution: {target_col}")
|
|
102
|
+
plt.xlabel("Class")
|
|
103
|
+
plt.ylabel("Count")
|
|
104
|
+
plt.tight_layout()
|
|
105
|
+
plt.show()
|
|
106
|
+
|
|
107
|
+
# 10. Separate Features and Target
|
|
108
|
+
X = df.drop(columns=[target_col]).copy()
|
|
109
|
+
y_original = df[target_col].copy()
|
|
110
|
+
|
|
111
|
+
if X.shape[1] == 0:
|
|
112
|
+
raise SystemExit("No feature columns remain.")
|
|
113
|
+
|
|
114
|
+
# 11. Process Date Columns
|
|
115
|
+
for col in list(X.columns):
|
|
116
|
+
if pd.api.types.is_datetime64_any_dtype(X[col]):
|
|
117
|
+
X[f"{col}_year"] = X[col].dt.year
|
|
118
|
+
X[f"{col}_month"] = X[col].dt.month
|
|
119
|
+
X[f"{col}_day"] = X[col].dt.day
|
|
120
|
+
X = X.drop(columns=[col])
|
|
121
|
+
|
|
122
|
+
# 12. Convert Numeric-Like Object Columns
|
|
123
|
+
for col in X.select_dtypes(
|
|
124
|
+
include=["object", "string"]
|
|
125
|
+
).columns:
|
|
126
|
+
converted = pd.to_numeric(
|
|
127
|
+
X[col],
|
|
128
|
+
errors="coerce"
|
|
129
|
+
)
|
|
130
|
+
if converted.notna().mean() >= 0.90:
|
|
131
|
+
X[col] = converted
|
|
132
|
+
|
|
133
|
+
# Remove columns containing only missing values
|
|
134
|
+
X = X.dropna(axis=1, how="all")
|
|
135
|
+
|
|
136
|
+
# 13. Encode Target Labels
|
|
137
|
+
encoder = LabelEncoder()
|
|
138
|
+
y = encoder.fit_transform(
|
|
139
|
+
y_original.astype(str)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
class_names = [
|
|
143
|
+
str(value) for value in encoder.classes_
|
|
144
|
+
]
|
|
145
|
+
n_classes = len(class_names)
|
|
146
|
+
|
|
147
|
+
print("\nTarget class encoding:")
|
|
148
|
+
for index, class_name in enumerate(class_names):
|
|
149
|
+
print(f"{class_name} -> {index}")
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# 1. Import Libraries
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from sklearn.model_selection import train_test_split
|
|
6
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
7
|
+
|
|
8
|
+
from tensorflow.keras.models import Sequential
|
|
9
|
+
from tensorflow.keras.layers import Dense, Dropout
|
|
10
|
+
from tensorflow.keras.callbacks import EarlyStopping
|
|
11
|
+
|
|
12
|
+
# 2. Load and Clean Dataset
|
|
13
|
+
df = pd.read_csv(
|
|
14
|
+
"/content/spam (1).csv",
|
|
15
|
+
encoding="latin-1"
|
|
16
|
+
)
|
|
17
|
+
df = df[["v1", "v2"]].copy()
|
|
18
|
+
df.columns = ["label", "text"]
|
|
19
|
+
|
|
20
|
+
# Remove missing values and duplicate rows
|
|
21
|
+
df.dropna(inplace=True)
|
|
22
|
+
df.drop_duplicates(inplace=True)
|
|
23
|
+
|
|
24
|
+
# Encode target labels: ham = 0, spam = 1
|
|
25
|
+
df["label"] = df["label"].map({
|
|
26
|
+
"ham": 0,
|
|
27
|
+
"spam": 1
|
|
28
|
+
})
|
|
29
|
+
df.dropna(subset=["label"], inplace=True)
|
|
30
|
+
df["label"] = df["label"].astype(int)
|
|
31
|
+
|
|
32
|
+
# Display dataset information
|
|
33
|
+
print("Dataset Shape:", df.shape)
|
|
34
|
+
print(df.head())
|
|
35
|
+
print("Class Counts:\n", df["label"].value_counts())
|
|
36
|
+
|
|
37
|
+
# 3. Train-Test Split
|
|
38
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
39
|
+
df["text"],
|
|
40
|
+
df["label"],
|
|
41
|
+
test_size=0.20,
|
|
42
|
+
random_state=42,
|
|
43
|
+
stratify=df["label"]
|
|
44
|
+
)
|
|
45
|
+
print("Training Samples:", len(X_train))
|
|
46
|
+
print("Testing Samples:", len(X_test))
|
|
47
|
+
|
|
48
|
+
# 4. TF-IDF Vectorization
|
|
49
|
+
vectorizer = TfidfVectorizer(
|
|
50
|
+
max_features=5000,
|
|
51
|
+
stop_words="english"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
X_train_nn = vectorizer.fit_transform(
|
|
55
|
+
X_train
|
|
56
|
+
).toarray().astype(np.float32)
|
|
57
|
+
|
|
58
|
+
X_test_nn = vectorizer.transform(
|
|
59
|
+
X_test
|
|
60
|
+
).toarray().astype(np.float32)
|
|
61
|
+
|
|
62
|
+
# Convert labels to NumPy arrays
|
|
63
|
+
y_train = y_train.to_numpy(dtype=np.float32)
|
|
64
|
+
y_test = y_test.to_numpy(dtype=np.float32)
|
|
65
|
+
print("Training Shape:", X_train_nn.shape)
|
|
66
|
+
print("Testing Shape:", X_test_nn.shape)
|
|
67
|
+
|
|
68
|
+
# 5. Function to Build Neural Network
|
|
69
|
+
def build_model(dropout=0.5, input_size=None):
|
|
70
|
+
model = Sequential([
|
|
71
|
+
Dense(
|
|
72
|
+
64,
|
|
73
|
+
activation="relu",
|
|
74
|
+
input_shape=(input_size,)
|
|
75
|
+
),
|
|
76
|
+
Dropout(dropout),
|
|
77
|
+
|
|
78
|
+
Dense(32, activation="relu"),
|
|
79
|
+
Dropout(dropout),
|
|
80
|
+
|
|
81
|
+
Dense(1, activation="sigmoid")
|
|
82
|
+
])
|
|
83
|
+
|
|
84
|
+
model.compile(
|
|
85
|
+
optimizer="adam",
|
|
86
|
+
loss="binary_crossentropy",
|
|
87
|
+
metrics=["accuracy"]
|
|
88
|
+
)
|
|
89
|
+
return model
|
|
90
|
+
|
|
91
|
+
# Early Stopping Callback
|
|
92
|
+
early_stop = EarlyStopping(
|
|
93
|
+
monitor="val_loss",
|
|
94
|
+
patience=3,
|
|
95
|
+
restore_best_weights=True
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# 6. Train Baseline Model on All Labelled Training Data
|
|
99
|
+
model = build_model(
|
|
100
|
+
dropout=0.5,
|
|
101
|
+
input_size=X_train_nn.shape[1]
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
model.fit(
|
|
105
|
+
X_train_nn,
|
|
106
|
+
y_train,
|
|
107
|
+
epochs=20,
|
|
108
|
+
batch_size=32,
|
|
109
|
+
validation_split=0.20,
|
|
110
|
+
callbacks=[early_stop],
|
|
111
|
+
verbose=1
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Evaluate baseline model
|
|
115
|
+
baseline_loss, baseline_accuracy = model.evaluate(
|
|
116
|
+
X_test_nn,
|
|
117
|
+
y_test,
|
|
118
|
+
verbose=0
|
|
119
|
+
)
|
|
120
|
+
print("Baseline Test Loss:", round(baseline_loss, 4))
|
|
121
|
+
print(
|
|
122
|
+
"Baseline Test Accuracy:",
|
|
123
|
+
round(baseline_accuracy * 100, 2),
|
|
124
|
+
"%"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
# 7. Split Training Data into Labelled and Unlabelled
|
|
128
|
+
X_labeled, X_unlabeled, y_labeled, y_unlabeled = train_test_split(
|
|
129
|
+
X_train_nn,
|
|
130
|
+
y_train,
|
|
131
|
+
test_size=0.70,
|
|
132
|
+
random_state=42,
|
|
133
|
+
stratify=y_train
|
|
134
|
+
)
|
|
135
|
+
print("Labelled Samples:", len(X_labeled))
|
|
136
|
+
print("Unlabelled Samples:", len(X_unlabeled))
|
|
137
|
+
|
|
138
|
+
# 8. Weak Augmentation and Train SSL Model
|
|
139
|
+
X_labeled_weak = X_labeled + np.random.normal(
|
|
140
|
+
loc=0,
|
|
141
|
+
scale=0.02,
|
|
142
|
+
size=X_labeled.shape
|
|
143
|
+
).astype(np.float32)
|
|
144
|
+
|
|
145
|
+
ssl_model = build_model(
|
|
146
|
+
dropout=0.3,
|
|
147
|
+
input_size=X_labeled.shape[1]
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
ssl_model.fit(
|
|
151
|
+
X_labeled_weak,
|
|
152
|
+
y_labeled,
|
|
153
|
+
epochs=20,
|
|
154
|
+
batch_size=32,
|
|
155
|
+
validation_split=0.20,
|
|
156
|
+
callbacks=[early_stop],
|
|
157
|
+
verbose=1
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# 9. Generate Pseudo-Labels for Unlabelled Data
|
|
161
|
+
pseudo_probs = ssl_model.predict(
|
|
162
|
+
X_unlabeled,
|
|
163
|
+
verbose=0
|
|
164
|
+
).flatten()
|
|
165
|
+
threshold = 0.90
|
|
166
|
+
|
|
167
|
+
# Select high-confidence predictions
|
|
168
|
+
mask = (
|
|
169
|
+
(pseudo_probs >= threshold)
|
|
170
|
+
| (pseudo_probs <= 1 - threshold)
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
X_pseudo = X_unlabeled[mask]
|
|
174
|
+
y_pseudo = (
|
|
175
|
+
pseudo_probs[mask] >= 0.5
|
|
176
|
+
).astype(np.float32)
|
|
177
|
+
|
|
178
|
+
print("Unlabelled Samples:", len(X_unlabeled))
|
|
179
|
+
print(
|
|
180
|
+
"High-Confidence Pseudo-Labelled Samples:",
|
|
181
|
+
len(X_pseudo)
|
|
182
|
+
)
|
|
183
|
+
print(
|
|
184
|
+
"Remaining Unused Unlabelled Samples:",
|
|
185
|
+
len(X_unlabeled) - len(X_pseudo)
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
# 10. Strong Augmentation and Combine Data
|
|
189
|
+
X_pseudo_strong = X_pseudo + np.random.normal(
|
|
190
|
+
loc=0,
|
|
191
|
+
scale=0.05,
|
|
192
|
+
size=X_pseudo.shape
|
|
193
|
+
).astype(np.float32)
|
|
194
|
+
|
|
195
|
+
# Combine labelled and pseudo-labelled samples
|
|
196
|
+
X_final = np.vstack((
|
|
197
|
+
X_labeled,
|
|
198
|
+
X_pseudo_strong
|
|
199
|
+
))
|
|
200
|
+
|
|
201
|
+
y_final = np.concatenate((
|
|
202
|
+
y_labeled,
|
|
203
|
+
y_pseudo
|
|
204
|
+
))
|
|
205
|
+
print("Final Training Samples:", len(X_final))
|
|
206
|
+
print("Final Label Shape:", y_final.shape)
|
|
207
|
+
|
|
208
|
+
# 11. Train Final Model
|
|
209
|
+
final_model = build_model(
|
|
210
|
+
dropout=0.3,
|
|
211
|
+
input_size=X_final.shape[1]
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
final_model.fit(
|
|
215
|
+
X_final,
|
|
216
|
+
y_final,
|
|
217
|
+
epochs=20,
|
|
218
|
+
batch_size=32,
|
|
219
|
+
validation_split=0.20,
|
|
220
|
+
callbacks=[early_stop],
|
|
221
|
+
verbose=1
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# 12. Evaluate and Compare Models
|
|
225
|
+
ssl_loss, ssl_accuracy = final_model.evaluate(
|
|
226
|
+
X_test_nn,
|
|
227
|
+
y_test,
|
|
228
|
+
verbose=0
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
print("SSL Test Loss:", round(ssl_loss, 4))
|
|
232
|
+
print(
|
|
233
|
+
"SSL Test Accuracy:",
|
|
234
|
+
round(ssl_accuracy * 100, 2),
|
|
235
|
+
"%"
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
print(
|
|
239
|
+
"Baseline Accuracy:",
|
|
240
|
+
round(baseline_accuracy * 100, 2),
|
|
241
|
+
"%"
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
# 13. Compare Model Performance
|
|
245
|
+
if ssl_accuracy > baseline_accuracy:
|
|
246
|
+
print("Semi-Supervised Learning Improved the Model.")
|
|
247
|
+
|
|
248
|
+
elif ssl_accuracy < baseline_accuracy:
|
|
249
|
+
print("Baseline Model Performed Better.")
|
|
250
|
+
|
|
251
|
+
else:
|
|
252
|
+
print("Both Models Performed Equally.")
|