code stringlengths 17 6.64M |
|---|
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train, num_epochs):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuf... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train, num_epochs):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = ['Neural Networks', 'Case Based', 'Reinforcement Learning', 'Probabilistic Methods', 'Genetic Algorithms', 'Rule Learning', 'Theory']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)... |
def RunAllTests(percentTraining, num_times, num_epochs):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, t... |
def getFeaturesTrainingData():
i = 0
lists = []
labels = []
for vertex in G.nodes:
vertex_embedding_list = []
lists.append({'f': vertex_features[vertex].tolist()})
labels.append(vertex_labels[vertex])
X_unshuffled = []
for hlist in lists:
x = np.zeros((feature_d... |
def getTrainingData():
i = 0
lists = []
labels = []
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
ver... |
def getMLPTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()})
label = np.zeros((n... |
def getDSTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
... |
def hyperedgesTrain(X_train, Y_train):
deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5'))
history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0, verbose=0)... |
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, va... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num_epochs, bat... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = target_names = ['Type-1 Diabetes', 'Type-2 Diabetes', 'Type-3 Diabetes']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)
finals_pred = []
finals_test = []
for p in y_pre... |
def RunAllTests(percentTraining, num_times=10):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, test_size=... |
def smooth(scalars, weight):
last = scalars[0]
smoothed = list()
for point in scalars:
smoothed_val = ((last * weight) + ((1 - weight) * point))
smoothed.append(smoothed_val)
last = smoothed_val
return smoothed
|
def plot(deephyperedges_directory, MLP_directory, deepsets_directory, metric, dataset):
dhe_metrics = pd.read_csv(deephyperedges_directory)
x = []
y = []
for (index, row) in dhe_metrics.iterrows():
x.append(float(row['Step']))
y.append(float(row['Value']))
mlp_metrics = pd.read_csv... |
def plotAll(dataset):
metric = 'run-.-tag-categorical_accuracy.csv'
deephyperedges_directory = ((('images/paper/' + dataset) + '/deephyperedges/') + metric)
MLP_directory = ((('images/paper/' + dataset) + '/MLP/') + metric)
deepsets_directory = ((('images/paper/' + dataset) + '/deepsets/') + metric)
... |
def skip_submodules(app, what, name, obj, skip, options):
return (name.endswith('__init__') or name.startswith('diart.console') or name.startswith('diart.argdoc'))
|
def setup(sphinx):
sphinx.connect('autoapi-skip-member', skip_submodules)
|
class AudioLoader():
def __init__(self, sample_rate: int, mono: bool=True):
self.sample_rate = sample_rate
self.mono = mono
def load(self, filepath: FilePath) -> torch.Tensor:
'Load an audio file into a torch.Tensor.\n\n Parameters\n ----------\n filepath : FileP... |
class AggregationStrategy(ABC):
'Abstract class representing a strategy to aggregate overlapping buffers\n\n Parameters\n ----------\n cropping_mode: ("strict", "loose", "center"), optional\n Defines the mode to crop buffer chunks as in pyannote.core.\n See https://pyannote.github.io/pyanno... |
class HammingWeightedAverageStrategy(AggregationStrategy):
'Compute the average weighted by the corresponding Hamming-window aligned to each buffer'
def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray:
(num_frames, num_speakers) = buffers[0].data.shape
(hamm... |
class AverageStrategy(AggregationStrategy):
'Compute a simple average over the focus region'
def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray:
intersection = np.stack([buffer.crop(focus, mode=self.cropping_mode, fixed=focus.duration) for buffer in buffers])
... |
class FirstOnlyStrategy(AggregationStrategy):
'Instead of aggregating, keep the first focus region in the buffer list'
def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray:
return buffers[0].crop(focus, mode=self.cropping_mode, fixed=focus.duration)
|
class DelayedAggregation():
'Aggregate aligned overlapping windows of the same duration\n across sliding buffers with a specific step and latency.\n\n Parameters\n ----------\n step: float\n Shift between two consecutive buffers, in seconds.\n latency: float, optional\n Desired latenc... |
@dataclass
class HyperParameter():
'Represents a pipeline hyper-parameter that can be tuned by diart'
name: Text
'Name of the hyper-parameter (e.g. tau_active)'
low: float
'Lowest value that this parameter can take'
high: float
'Highest value that this parameter can take'
@staticmetho... |
class PipelineConfig(ABC):
'Configuration containing the required\n parameters to build and run a pipeline'
@property
@abstractmethod
def duration(self) -> float:
'The duration of an input audio chunk (in seconds)'
pass
@property
@abstractmethod
def step(self) -> float... |
class Pipeline(ABC):
'Represents a streaming audio pipeline'
@staticmethod
@abstractmethod
def get_config_class() -> type:
pass
@staticmethod
@abstractmethod
def suggest_metric() -> BaseMetric:
pass
@staticmethod
@abstractmethod
def hyper_parameters() -> Sequ... |
class SpeakerDiarizationConfig(base.PipelineConfig):
def __init__(self, segmentation: (m.SegmentationModel | None)=None, embedding: (m.EmbeddingModel | None)=None, duration: float=5, step: float=0.5, latency: ((float | Literal[('max', 'min')]) | None)=None, tau_active: float=0.6, rho_update: float=0.3, delta_new... |
class SpeakerDiarization(base.Pipeline):
def __init__(self, config: (SpeakerDiarizationConfig | None)=None):
self._config = (SpeakerDiarizationConfig() if (config is None) else config)
msg = f'Latency should be in the range [{self._config.step}, {self._config.duration}]'
assert (self._con... |
class SpeakerEmbedding():
def __init__(self, model: EmbeddingModel, device: Optional[torch.device]=None):
self.model = model
self.model.eval()
self.device = device
if (self.device is None):
self.device = torch.device('cpu')
self.model.to(self.device)
se... |
class OverlappedSpeechPenalty():
'Applies a penalty on overlapping speech and low-confidence regions to speaker segmentation scores.\n\n .. note::\n For more information, see `"Overlap-Aware Low-Latency Online Speaker Diarization\n based on End-to-End Local Segmentation" <https://github.com/juanm... |
class EmbeddingNormalization():
def __init__(self, norm: Union[(float, torch.Tensor)]=1):
self.norm = norm
if (isinstance(self.norm, torch.Tensor) and (self.norm.ndim == 2)):
self.norm = self.norm.unsqueeze(0)
def __call__(self, embeddings: torch.Tensor) -> torch.Tensor:
... |
class OverlapAwareSpeakerEmbedding():
"\n Extract overlap-aware speaker embeddings given an audio chunk and its segmentation.\n\n Parameters\n ----------\n model: EmbeddingModel\n A pre-trained embedding model.\n gamma: float, optional\n Exponent to lower low-confidence predictions.\n... |
class SpeakerSegmentation():
def __init__(self, model: SegmentationModel, device: Optional[torch.device]=None):
self.model = model
self.model.eval()
self.device = device
if (self.device is None):
self.device = torch.device('cpu')
self.model.to(self.device)
... |
class Binarize():
'\n Transform a speaker segmentation from the discrete-time domain\n into a continuous-time speaker segmentation.\n\n Parameters\n ----------\n threshold: float\n Probability threshold to determine if a speaker is active at a given frame.\n uri: Optional[Text]\n U... |
class Resample():
'Dynamically resample audio chunks.\n\n Parameters\n ----------\n sample_rate: int\n Original sample rate of the input audio\n resample_rate: int\n Sample rate of the output\n '
def __init__(self, sample_rate: int, resample_rate: int, device: Optional[torch.devi... |
class AdjustVolume():
'Change the volume of an audio chunk.\n\n Notice that the output volume might be different to avoid saturation.\n\n Parameters\n ----------\n volume_in_db: float\n Target volume in dB.\n '
def __init__(self, volume_in_db: float):
self.target_db = volume_in_... |
class VoiceActivityDetectionConfig(base.PipelineConfig):
def __init__(self, segmentation: (m.SegmentationModel | None)=None, duration: float=5, step: float=0.5, latency: ((float | Literal[('max', 'min')]) | None)=None, tau_active: float=0.6, device: (torch.device | None)=None, sample_rate: int=16000, **kwargs):
... |
class VoiceActivityDetection(base.Pipeline):
def __init__(self, config: (VoiceActivityDetectionConfig | None)=None):
self._config = (VoiceActivityDetectionConfig() if (config is None) else config)
msg = f'Latency should be in the range [{self._config.step}, {self._config.duration}]'
asser... |
def run():
parser = argparse.ArgumentParser()
parser.add_argument('root', type=Path, help='Directory with audio files CONVERSATION.(wav|flac|m4a|...)')
parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline to optimize. Defaults to 'SpeakerDiarization'")
... |
def send_audio(ws: WebSocket, source: Text, step: float, sample_rate: int):
source_components = source.split(':')
if (source_components[0] != 'microphone'):
audio_source = src.FileAudioSource(source, sample_rate, block_duration=step)
else:
device = (int(source_components[1]) if (len(source... |
def receive_audio(ws: WebSocket, output: Optional[Path]):
while True:
message = ws.recv()
print(f'Received: {message}', end='')
if (output is not None):
with open(output, 'a') as file:
file.write(message)
|
def run():
parser = argparse.ArgumentParser()
parser.add_argument('source', type=str, help="Path to an audio file | 'microphone' | 'microphone:<DEVICE_ID>'")
parser.add_argument('--host', required=True, type=str, help='Server host')
parser.add_argument('--port', required=True, type=int, help='Server p... |
def run():
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='0.0.0.0', type=str, help='Server host')
parser.add_argument('--port', default=7007, type=int, help='Server port')
parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline t... |
def run():
parser = argparse.ArgumentParser()
parser.add_argument('source', type=str, help="Path to an audio file | 'microphone' | 'microphone:<DEVICE_ID>'")
parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline to optimize. Defaults to 'SpeakerDiarization'"... |
def run():
parser = argparse.ArgumentParser()
parser.add_argument('root', type=str, help='Directory with audio files CONVERSATION.(wav|flac|m4a|...)')
parser.add_argument('--reference', required=True, type=str, help='Directory with RTTM files CONVERSATION.rttm. Names must match audio files')
parser.ad... |
class TemporalFeatureFormatterState(ABC):
'\n Represents the recorded type of a temporal feature formatter.\n Its job is to transform temporal features into tensors and\n recover the original format on other features.\n '
@abstractmethod
def to_tensor(self, features: TemporalFeatures) -> torc... |
class SlidingWindowFeatureFormatterState(TemporalFeatureFormatterState):
def __init__(self, duration: float):
self.duration = duration
self._cur_start_time = 0
def to_tensor(self, features: SlidingWindowFeature) -> torch.Tensor:
msg = 'Features sliding window duration and step must b... |
class NumpyArrayFormatterState(TemporalFeatureFormatterState):
def to_tensor(self, features: np.ndarray) -> torch.Tensor:
return torch.from_numpy(features)
def to_internal_type(self, features: torch.Tensor) -> TemporalFeatures:
return features.cpu().numpy()
|
class PytorchTensorFormatterState(TemporalFeatureFormatterState):
def to_tensor(self, features: torch.Tensor) -> torch.Tensor:
return features
def to_internal_type(self, features: torch.Tensor) -> TemporalFeatures:
return features
|
class TemporalFeatureFormatter():
'\n Manages the typing and format of temporal features.\n When casting temporal features as torch.Tensor, it remembers its\n type and format so it can lately restore it on other temporal features.\n '
def __init__(self):
self.state: Optional[TemporalFeatu... |
def overlapped_speech_penalty(segmentation: torch.Tensor, gamma: float=3, beta: float=10):
probs = torch.softmax((beta * segmentation), dim=(- 1))
weights = (torch.pow(segmentation, gamma) * torch.pow(probs, gamma))
weights[(weights < 1e-08)] = 1e-08
return weights
|
def normalize_embeddings(embeddings: torch.Tensor, norm: (float | torch.Tensor)=1) -> torch.Tensor:
if (embeddings.ndim == 2):
embeddings = embeddings.unsqueeze(0)
if isinstance(norm, torch.Tensor):
(batch_size1, num_speakers1, _) = norm.shape
(batch_size2, num_speakers2, _) = embeddin... |
class StreamingInference():
"Performs inference in real time given a pipeline and an audio source.\n Streams an audio source to an online speaker diarization pipeline.\n It allows users to attach a chain of operations in the form of hooks.\n\n Parameters\n ----------\n pipeline: StreamingPipeline\n... |
class Benchmark():
'\n Run an online speaker diarization pipeline on a set of audio files in batches.\n Write predictions to a given output directory.\n\n If the reference is given, calculate the average diarization error rate.\n\n Parameters\n ----------\n speech_path: Text or Path\n Dir... |
class Parallelize():
'Wrapper to parallelize the execution of a `Benchmark` instance.\n Note that models will be copied in each worker instead of being reused.\n\n Parameters\n ----------\n benchmark: Benchmark\n Benchmark instance to execute in parallel.\n num_workers: int\n Number o... |
class PowersetAdapter(nn.Module):
def __init__(self, segmentation_model: nn.Module):
super().__init__()
self.model = segmentation_model
specs = self.model.specifications
max_speakers_per_frame = specs.powerset_max_classes
max_speakers_per_chunk = len(specs.classes)
... |
class PyannoteLoader():
def __init__(self, model_info, hf_token: Union[(Text, bool, None)]=True):
super().__init__()
self.model_info = model_info
self.hf_token = hf_token
def __call__(self) -> Callable:
try:
model = Model.from_pretrained(self.model_info, use_auth_... |
class ONNXLoader():
def __init__(self, path: (str | Path), input_names: List[str], output_name: str):
super().__init__()
self.path = Path(path)
self.input_names = input_names
self.output_name = output_name
def __call__(self) -> ONNXModel:
return ONNXModel(self.path, s... |
class ONNXModel():
def __init__(self, path: Path, input_names: List[str], output_name: str):
super().__init__()
self.path = path
self.input_names = input_names
self.output_name = output_name
self.device = torch.device('cpu')
self.session = None
self.recreat... |
class LazyModel(ABC):
def __init__(self, loader: Callable[([], Callable)]):
super().__init__()
self.get_model = loader
self.model: Optional[Callable] = None
def is_in_memory(self) -> bool:
'Return whether the model has been loaded into memory'
return (self.model is no... |
class SegmentationModel(LazyModel):
'\n Minimal interface for a segmentation model.\n '
@staticmethod
def from_pyannote(model, use_hf_token: Union[(Text, bool, None)]=True) -> 'SegmentationModel':
'\n Returns a `SegmentationModel` wrapping a pyannote model.\n\n Parameters\n ... |
class EmbeddingModel(LazyModel):
'Minimal interface for an embedding model.'
@staticmethod
def from_pyannote(model, use_hf_token: Union[(Text, bool, None)]=True) -> 'EmbeddingModel':
'\n Returns an `EmbeddingModel` wrapping a pyannote model.\n\n Parameters\n ----------\n ... |
class Optimizer():
def __init__(self, pipeline_class: type, speech_path: Union[(Text, Path)], reference_path: Union[(Text, Path)], study_or_path: Union[(FilePath, Study)], batch_size: int=32, hparams: Optional[Sequence[blocks.base.HyperParameter]]=None, base_config: Optional[blocks.PipelineConfig]=None, do_kicks... |
class ProgressBar(ABC):
@abstractmethod
def create(self, total: int, description: Optional[Text]=None, unit: Text='it', **kwargs):
pass
@abstractmethod
def start(self):
pass
@abstractmethod
def update(self, n: int=1):
pass
@abstractmethod
def write(self, tex... |
class RichProgressBar(ProgressBar):
def __init__(self, description: Optional[Text]=None, color: Text='green', leave: bool=True, do_close: bool=True):
self.description = description
self.color = color
self.do_close = do_close
self.bar = Progress(transient=(not leave))
self.... |
class TQDMProgressBar(ProgressBar):
def __init__(self, description: Optional[Text]=None, leave: bool=True, position: Optional[int]=None, do_close: bool=True):
self.description = description
self.leave = leave
self.position = position
self.do_close = do_close
self.pbar: Opt... |
class WindowClosedException(Exception):
pass
|
def _extract_prediction(value: Union[(Tuple, Annotation)]) -> Annotation:
if isinstance(value, tuple):
return value[0]
if isinstance(value, Annotation):
return value
msg = f'Expected tuple or Annotation, but got {type(value)}'
raise ValueError(msg)
|
class RTTMWriter(Observer):
def __init__(self, uri: Text, path: Union[(Path, Text)], patch_collar: float=0.05):
super().__init__()
self.uri = uri
self.patch_collar = patch_collar
self.path = Path(path).expanduser()
if self.path.exists():
self.path.unlink()
... |
class PredictionAccumulator(Observer):
def __init__(self, uri: Optional[Text]=None, patch_collar: float=0.05):
super().__init__()
self.uri = uri
self.patch_collar = patch_collar
self._prediction: Optional[Annotation] = None
def patch(self):
'Stitch same-speaker turns ... |
class StreamingPlot(Observer):
def __init__(self, duration: float, latency: float, visualization: Literal[('slide', 'accumulate')]='slide', reference: Optional[Union[(Path, Text)]]=None):
super().__init__()
assert (visualization in ['slide', 'accumulate'])
self.visualization = visualizati... |
class Chronometer():
def __init__(self, unit: Text, progress_bar: Optional[ProgressBar]=None):
self.unit = unit
self.progress_bar = progress_bar
self.current_start_time = None
self.history = []
@property
def is_running(self):
return (self.current_start_time is not... |
def parse_hf_token_arg(hf_token: Union[(bool, Text)]) -> Union[(bool, Text)]:
if isinstance(hf_token, bool):
return hf_token
if (hf_token.lower() == 'true'):
return True
if (hf_token.lower() == 'false'):
return False
return hf_token
|
def encode_audio(waveform: np.ndarray) -> Text:
data = waveform.astype(np.float32).tobytes()
return base64.b64encode(data).decode('utf-8')
|
def decode_audio(data: Text) -> np.ndarray:
byte_samples = base64.decodebytes(data.encode('utf-8'))
samples = np.frombuffer(byte_samples, dtype=np.float32)
return samples.reshape(1, (- 1))
|
def get_padding_left(stream_duration: float, chunk_duration: float) -> float:
if (stream_duration < chunk_duration):
return (chunk_duration - stream_duration)
return 0
|
def repeat_label(label: Text):
while True:
(yield label)
|
def get_pipeline_class(class_name: Text) -> type:
pipeline_class = getattr(blocks, class_name, None)
msg = f"Pipeline '{class_name}' doesn't exist"
assert (pipeline_class is not None), msg
return pipeline_class
|
def get_padding_right(latency: float, step: float) -> float:
return (latency - step)
|
def visualize_feature(duration: Optional[float]=None):
def apply(feature: SlidingWindowFeature):
if (duration is None):
notebook.crop = feature.extent
else:
notebook.crop = Segment((feature.extent.end - duration), feature.extent.end)
plt.rcParams['figure.figsize'] ... |
def visualize_annotation(duration: Optional[float]=None):
def apply(annotation: Annotation):
extent = annotation.get_timeline().extent()
if (duration is None):
notebook.crop = extent
else:
notebook.crop = Segment((extent.end - duration), extent.end)
plt.rcP... |
class Boco():
def __init__(self, name):
self.name = name
def validate(self):
assert self.computeLoss, 'You need to specify a function to compute the loss'
|
class Neumann(Boco):
def __init__(self, sampler, name='neumann'):
super().__init__(name)
self.vars = sampler.vars
self.sampler = sampler
def sample(self, n_samples=None):
return self.sampler.sample(n_samples)
def validate(self, inputs, outputs):
super().validate(... |
class Periodic(Boco):
def __init__(self, sampler, sampler1, sampler2, name='periodic'):
super().__init__(name)
self.sampler = sampler
self.sampler1 = sampler1
self.sampler2 = sampler2
inputs1 = tuple(self.sampler1.sample(1).keys())
inputs2 = tuple(self.sampler2.sam... |
class Dataset(torch.utils.data.Dataset):
def __init__(self, data, device='cpu'):
mesh = np.stack(np.meshgrid(*data), (- 1)).reshape((- 1), len(data))
self.X = torch.from_numpy(mesh).float().to(device)
def __len__(self):
return len(self.X)
def __getitem__(self, ix):
retur... |
class Mesh():
def __init__(self, data, device='cpu'):
assert isinstance(data, dict), 'you must pass a dict with your data'
(self.vars, data) = (tuple(data.keys()), data.values())
self.dataset = Dataset(data, device)
self.device = device
def build_dataloader(self, batch_size=N... |
class History():
def __init__(self, precision=5):
self.history = {}
self.current = {}
self.precision = precision
def add(self, d):
for (name, metric) in d.items():
if (not (name in self.history)):
self.history[name] = []
self.history[na... |
class Sine(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return torch.sin(x)
|
def block(i, o):
fc = torch.nn.Linear(i, o)
return torch.nn.Sequential(Sine(), torch.nn.Linear(i, o))
|
class MLP(torch.nn.Module):
def __init__(self, inputs, outputs, layers, neurons):
super().__init__()
fc_in = torch.nn.Linear(inputs, neurons)
fc_hidden = [block(neurons, neurons) for layer in range((layers - 1))]
fc_out = block(neurons, outputs)
self.mlp = torch.nn.Sequent... |
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
|
class PDE():
def __init__(self, inputs, outputs):
if isinstance(inputs, str):
inputs = tuple(inputs)
if isinstance(outputs, str):
outputs = tuple(outputs)
checkIsListOfStr(inputs)
checkIsListOfStr(outputs)
checkUnique(inputs)
checkUnique(out... |
class BaseSampler():
def __init__(self, data, n_samples=1, device='cpu'):
assert isinstance(data, dict), 'you must pass a dict with your data'
self.device = device
self.data = data
self.vars = tuple(data.keys())
self.n_samples = n_samples
def _sample(self, n_samples=N... |
class RandomSampler(BaseSampler):
def __init__(self, data, n_samples=1, device='cpu'):
super().__init__(data, n_samples, device)
for (var, lims) in data.items():
if isinstance(lims, list):
assert (len(lims) == 2), 'you must pass a list with the min and max limits'
... |
def checkIsListOfStr(l):
'Make sure that l is a list containing only strings'
if isinstance(l, tuple):
for i in l:
if (not isinstance(i, str)):
raise Exception((str(i) + ' must be a string'))
|
def checkUnique(l):
'Make sure that l does not contain repeated elements'
for (i, item1) in enumerate(l):
for (j, item2) in enumerate(l):
if ((i != j) and (item1 == item2)):
raise Exception(('Repeated item ' + str(item1)))
|
def checkNoRepeated(l1, l2):
'Make sure there are no repeated elements in both lists'
for i in l1:
if (i in l2):
raise Exception(('Repeated item ' + str(i)))
|
class EnvWrapper():
def __init__(self, task):
self.action_space = self.brain.vector_action_space_size
|
class CountScore():
def __init__(self):
self.total_episode = 100
self.episode_rewards = np.zeros(self.total_episode)
self.current_episode = 0
def add_score(self, score):
self.episode_rewards[self.current_episode] = score
self.current_episode += 1
self.current_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.