File size: 5,747 Bytes
29d330e | 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 | import matplotlib.pyplot as plt
import csv
from collections import OrderedDict
from typing import List, Tuple
import torch
import numpy as np
import subprocess
import os
from utils.Dataset import Jammer_Dataset
from torch.utils.data import DataLoader
from utils.Dataset import balance_data
import torch.nn.functional as F
def visualization(image, label):
# Create a plot
plt.figure(figsize=(10, 6)) # Adjust the figure size as needed
plt.imshow(image.permute(1, 2, 0), origin='lower')
plt.colorbar()
plt.title(f'Spectrogram of class {label} ')
plt.xlabel('Time')
plt.ylabel('Channel')
plt.show()
def save_balanced_data_to_csv(data, csv_filename):
# Create the folder if it doesn't exist
folder_path = "../Linkhalle_fewshot_dataset"
os.makedirs(folder_path, exist_ok=True)
csv_filepath = os.path.join(folder_path, csv_filename)
# Check if the file already exists
file_exists = os.path.isfile(csv_filepath)
# Check if data is not empty and the file doesn't exist
# print(f"data is following --------{data}")
if data and not file_exists:
with open(csv_filepath, 'w', newline='') as csvfile:
fieldnames = ['Filename', 'Label']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Write the header
writer.writeheader()
# Write the data
for filename, label in data:
writer.writerow({'Filename': filename, 'Label': label})
elif not data:
print("No data to save.")
elif file_exists:
print("File already exists. Data not written.")
def load_data_from_csv(csv_filename):
dataset_training = "../Linkhalle_fewshot_dataset"
csv_filepath = os.path.join(dataset_training, csv_filename)
data = []
with open(csv_filepath, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['Filename'] and row['Label']:
filename = row['Filename']
label = int(row['Label'])
data.append((filename, label))
return data
def update(data, target, model, optimizer):
model.send(data.location)
optimizer.zero_grad()
prediction = model(data)
loss = F.mse_loss(prediction.view(-1), target)
loss.backward()
optimizer.step()
return model
def get_parameters(net) -> List[np.ndarray]:
return [val.cpu().numpy() for _, val in net.state_dict().items()]
def set_parameters(net, parameters: List[np.ndarray]):
params_dict = zip(net.state_dict().keys(), parameters)
state_dict = OrderedDict({k: torch.Tensor(v) for k, v in params_dict})
net.load_state_dict(state_dict, strict=True)
def check_client_availability(client_name):
try:
# Run 'ping' command with a timeout of 2 seconds (adjust as needed)
subprocess.check_call(["ping", "-c", "1", "-W", "2", client_name])
return True # Client is reachable
except subprocess.CalledProcessError:
return False # Client is not reachable
def calculate_binary_metrics(true_labels, predicted_labels):
"""
Calculate binary classification metrics using NumPy.
"""
tp = np.sum(np.logical_and(predicted_labels == 1, true_labels == 1))
fp = np.sum(np.logical_and(predicted_labels == 1, true_labels == 0))
fn = np.sum(np.logical_and(predicted_labels == 0, true_labels == 1))
tn = np.sum(np.logical_and(predicted_labels == 0, true_labels == 0))
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1 = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
# F2 score with more emphasis on recall
beta = 2
f2 = (1 + beta**2) * (precision * recall) / ((beta**2 * precision) + recall) if (precision + recall) > 0 else 0
# Accuracy
accuracy = (tp + tn) / (tp + tn + fp + fn) if (tp + tn + fp + fn) > 0 else 0
return precision, recall, f1, f2, accuracy
def create_test_set(
root_dir,
train_test_split_dir
):
required_train_txt = ["test_files_0.8_0.8_0.8_0.8_0.8_0.8_0.0_0.8_0.8_0.8_0.8_0.8_split4.txt"]
# Initialize lists to store filenames and labels
print(f"required file ------------------------{required_train_txt}")
filenames = []
labels = []
for filename in required_train_txt:
with open(os.path.join(train_test_split_dir, filename), 'r') as file:
lines = file.readlines()
for line in lines:
parts = line.strip().split()
if len(parts) == 2:
filenames.append(os.path.join(root_dir, parts[0]))
labels.append(int(parts[1]))
# Randomly shuffle the data and labels
combined_data = list(zip(filenames, labels))
#random.shuffle(combined_data)
# combined_data = balance_data(n_shot,n_query,combined_data)
testing_path = "tesing_file"
os.makedirs(testing_path, exist_ok=True)
test_file = os.path.join(testing_path, f'tesing_data_{4}.csv')
save_balanced_data_to_csv(combined_data, test_file)
def create_test_dataloder(
root_dir,
path,
batch,
n_workers,
norm_vals,
transforms=None,
):
train_data = load_data_from_csv(path)
train_dataset = Jammer_Dataset(root_dir, train_data, norm_vals,transform=transforms)
# Create DataLoader for training
train_loader = DataLoader(
train_dataset,
batch_size=batch,
num_workers=n_workers,
pin_memory=True,
shuffle=False,
)
return train_loader
|