import os import numpy as np import pandas as pd from glob import glob from…
- User
import os import numpy as np import pandas as pd from glob import glob from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import LabelEncoder from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv1D, MaxPooling1D, Bidirectional, GRU, GlobalAveragePooling1D, Dense, InputLayer from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping from collections import defaultdict
=== Step 1: Load All Chunk Files ===
print("📂 Loading data...") input_dir = '/kaggle/input/final-dataset' all_files = sorted(glob(os.path.join(input_dir, "chunk_*_acc_pdt.csv")))
X_list = [] y_list = []
for file in all_files: print(f"→ Loading {os.path.basename(file)}") df = pd.read_csv(file)
code# Extract labels and features labels = df['superfamily'].values features = df.iloc[:, 2:].values.astype(np.float32) X_list.append(features) y_list.extend(labels)Combine all chunks
X_all = np.vstack(X_list) # Shape: (N, 9530) y_all = np.array(y_list) # Shape: (N,) print(f"✅ Combined shape: {X_all.shape}, Labels: {y_all.shape}")
Reshape features to (samples, 953, 10)
X_all = X_all.reshape((-1, 953, 10))
=== Step 2: Encode Labels ===
le = LabelEncoder() y_encoded = le.fit_transform(y_all) num_classes = len(np.unique(y_encoded))
=== Step 3: Organize by Superfamily for Fold Generation ===
superfamily_to_indices = defaultdict(list) for idx, label in enumerate(y_encoded): superfamily_to_indices[label].append(idx)
=== Step 4: Create 5 folds per superfamily ===
num_folds = 5 fold_indices = [[] for _ in range(num_folds)]
for sf_label, indices in superfamily_to_indices.items(): indices = np.array(indices) kf = StratifiedKFold(n_splits=num_folds, shuffle=True, random_state=42) y_dummy = [sf_label] * len(indices) # all same class for fold_id, (_, test_split) in enumerate(kf.split(indices, y_dummy)): fold_indices[fold_id].extend(indices[test_split])
this code load all the chunk data now i want you to keep only 1500 data from each superfamily
then store it to a csv called training.csv wher the file contain only superfamily and domain_id
from this csv compare loaded chunk and add those to training and testing data
then for each family split 7 to 3 training and testing data do not use kfold cross validation
- Assistant
- User
then i have model in which i have provided below just train and give me roc curve at the end
=== Step 5: Define CNN-BiGRU Model ===
def create_cnn_gru_model(input_shape=(953, 10), num_classes=40): model = Sequential([ InputLayer(input_shape=input_shape), Conv1D(filters=8, kernel_size=23, activation='relu'), MaxPooling1D(pool_size=2), Conv1D(filters=8, kernel_size=1, activation='relu'), MaxPooling1D(pool_size=2), Bidirectional(GRU(32, return_sequences=True)), GlobalAveragePooling1D(), Dense(32, activation='relu'), Dense(num_classes, activation='softmax') ]) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model
=== Step 6: Train on Each Fold ===
print("\n📊 Starting superfamily-wise 5-fold training...") for fold in range(num_folds): print(f"\n🔁 Fold {fold + 1}")
code - Assistant
- User
- Assistant
- User
You need to prepare/train/test CSV splits separately by family first. A CSV (like you initially generated) that contains explicit train/test splits per family, saved as train_sf.csv and test_sf.csv. If you don't have that done, do it before with exact 70/30 splits per family. We switch from multiclass to repeated binary classification per family to simplify ROC/AUC computation (one-vs-rest). There are rare cases, but when you train family-by-family, the output layer is 2 units (in-family vs out-of-family). It fits your request to get ROC/AUC per individual family. Reading domain_ids per family per chunk file efficiently to minimize memory use. If some chunk files are large, consider pandas chunksize parameter or preprocessing to make per-family CSVs once to speed up. Batch size, epochs, complexity: adjust for your GPU constraints. Maybe drop epochs if training takes too long. Reduce model complexity or add dropout regularization if overfitting. Final tips: Make sure domain_id values are unique and correctly map to rows. Use df_sampled before train/test split to avoid mismatches. Save per-family model and ROC/AUC to analyze later. Run code step-by-step and test on one small family to verify correctness and memory usage. Kaggle environments are limited: monitor RAM/gpu crashes through logs. If you want, I can also help make this a full pipeline with saving/loading models or optimize data loading with caching — just let me know!
- Assistant