SMAPSegLoader: A PyTorch Dataset for Soil Moisture Prediction
This code implements a SMAPSegLoader class, which inherits from PyTorch's Dataset class. It's designed for loading the SMAP dataset, containing soil moisture observations across the US, used for building soil moisture prediction models.
The __init__ method initializes the dataset's parameters, including the root directory, window size, step, and dataset type.
The __len__ method determines the dataset's length. For training, validation, or test sets, it returns the number of windows in the data. For the prediction set, it returns the number of windows plus one.
The __getitem__ method retrieves the sample and label corresponding to the specified index. For training, validation, or test sets, it returns the respective data and labels. For the prediction set, it returns the test data and corresponding labels.
class SMAPSegLoader(Dataset):
def __init__(self, root_path, win_size, step=1, flag='train'):
self.flag = flag
self.step = step
self.win_size = win_size
self.scaler = StandardScaler()
data = np.load(os.path.join(root_path, 'SMAP_train.npy'))
self.scaler.fit(data)
data = self.scaler.transform(data)
test_data = np.load(os.path.join(root_path, 'SMAP_test.npy'))
self.test = self.scaler.transform(test_data)
self.train = data
self.val = self.test
self.test_labels = np.load(os.path.join(root_path, 'SMAP_test_label.npy'))
print('test:', self.test.shape)
print('train:', self.train.shape)
def __len__(self):
if self.flag == 'train':
return (self.train.shape[0] - self.win_size) // self.step + 1
elif (self.flag == 'val'):
return (self.val.shape[0] - self.win_size) // self.step + 1
elif (self.flag == 'test'):
return (self.test.shape[0] - self.win_size) // self.step + 1
else:
return (self.test.shape[0] - self.win_size) // self.win_size + 1
def __getitem__(self, index):
index = index * self.step
if self.flag == 'train':
return np.float32(self.train[index:index + self.win_size]), np.float32(self.test_labels[0:self.win_size])
elif (self.flag == 'val'):
return np.float32(self.val[index:index + self.win_size]), np.float32(self.test_labels[0:self.win_size])
elif (self.flag == 'test'):
return np.float32(self.test[index:index + self.win_size]), np.float32(
self.test_labels[index:index + self.win_size])
else:
return np.float32(self.test[
index // self.step * self.win_size:index // self.step * self.win_size + self.win_size]), np.float32(
self.test_labels[index // self.step * self.win_size:index // self.step * self.win_size + self.win_size])
原文地址: https://www.cveoy.top/t/topic/m9kO 著作权归作者所有。请勿转载和采集!