FelixOtt's picture
Upload folder using huggingface_hub
29d330e verified
Raw History Blame Contribute Delete
5.75 kB
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