Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A 1D GAN learns to generate fixed-length sequences by training two neural networks in opposition: a generator maps random noise to synthetic sequences, and a discriminator learns to distinguish those sequences from real training examples. This tutorial builds a compact, unconditional baseline in Keras, trains it with an explicit alternating loop, and shows how to inspect its output. The architecture is a teaching example—not a universal recipe for stable or high-quality sequence generation.

Define the sequence format before building the GAN

Choose one consistent representation for every real example. With Keras Conv1D in its default channels-last format, a batch has shape (batch, steps, features): the number of examples, the sequence length, and the number of values recorded at each time step. For example, 64 sequences of 100 one-feature readings have shape (64, 100, 1). The Conv1D API documents this convention and the layer’s output dimensions.

Scale training values to match the generator’s final activation. A tanh output commonly pairs with data scaled to roughly -1 to 1; a sigmoid output pairs with nonnegative data scaled to 0 to 1. These are design choices, not guarantees of suitability for every dataset. Record the scaling parameters from the training split and apply the same transformation when interpreting generated samples.

The generator must return the same number of steps and features as real batches. Before training, check that real and generated tensors agree on length, feature count, dtype, and scale; otherwise the discriminator cannot compare like with like.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Build a generator and discriminator

The example uses dense layers to project noise into a sequence, then temporal convolutions to shape it. The discriminator uses temporal convolutions and produces one real/fake logit per sequence. This fixed-length design is intentionally straightforward; other valid designs use upsampling or a different convolutional stack, depending on sequence length and temporal structure.

import keras
from keras import layers

sequence_length = 100
feature_count = 1
latent_dim = 32


def make_generator():
    noise = keras.Input(shape=(latent_dim,))
    x = layers.Dense(sequence_length * 64, activation="relu")(noise)
    x = layers.Reshape((sequence_length, 64))(x)
    x = layers.Conv1D(64, kernel_size=5, padding="same", activation="relu")(x)
    x = layers.Conv1D(32, kernel_size=5, padding="same", activation="relu")(x)
    sequence = layers.Conv1D(
        feature_count, kernel_size=5, padding="same", activation="tanh"
    )(x)
    return keras.Model(noise, sequence, name="generator")


def make_discriminator():
    sequence = keras.Input(shape=(sequence_length, feature_count))
    x = layers.Conv1D(32, kernel_size=5, strides=2, padding="same")(sequence)
    x = layers.LeakyReLU(negative_slope=0.2)(x)
    x = layers.Conv1D(64, kernel_size=5, strides=2, padding="same")(x)
    x = layers.LeakyReLU(negative_slope=0.2)(x)
    x = layers.Flatten()(x)
    logit = layers.Dense(1)(x)
    return keras.Model(sequence, logit, name="discriminator")


generator = make_generator()
discriminator = make_discriminator()

The generator’s last convolution has one output channel because this example assumes one feature. Set feature_count to the dataset’s actual feature count. Its tanh activation means the example expects appropriately scaled values. If you change the data range or output activation, keep the two choices compatible.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

All three generator convolutions use padding="same" with stride 1, preserving sequence length. Keras also supports valid and causal padding. Causal padding prevents an output at time t from depending on later positions, which can matter for one-way time-dependent tasks. It is not automatically preferable when generating complete windows where context across the whole sequence is useful.

Train in alternating discriminator and generator phases

In the discriminator phase, train on real sequences with real targets and generated sequences with fake targets. In the generator phase, generate a fresh batch and update the generator so the discriminator assigns those samples real targets. Goodfellow and coauthors describe the generator’s objective as maximizing the probability that the discriminator makes a mistake: “The training procedure for G is to maximize the probability of D making a mistake.” (Generative Adversarial Networks, submitted June 10, 2014.)

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

The code below uses binary cross-entropy from logits and a manual GradientTape loop. It assumes a TensorFlow-backed Keras installation, as tf.GradientTape is TensorFlow-specific. Keras 3 supports JAX, TensorFlow, and PyTorch backends, so this training loop is not backend-neutral; the gradient and optimizer code must be adapted for another backend. See Keras’s backend information.

import tensorflow as tf

# real_train must be a float tensor/array shaped
# (number_of_examples, sequence_length, feature_count),
# scaled consistently with the generator output.
real_train = tf.convert_to_tensor(real_train, dtype=tf.float32)

batch_size = 64
epochs = 100
steps_per_epoch = int(real_train.shape[0]) // batch_size

real_targets = tf.ones((batch_size, 1))
fake_targets = tf.zeros((batch_size, 1))
loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)

g_optimizer = keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5)
d_optimizer = keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5)

@tf.function
def train_step(real_batch):
    batch_size_now = tf.shape(real_batch)[0]

    # Update discriminator on real and generated sequences.
    noise = tf.random.normal((batch_size_now, latent_dim))
    fake_batch = generator(noise, training=True)
    with tf.GradientTape() as tape:
        real_logits = discriminator(real_batch, training=True)
        fake_logits = discriminator(fake_batch, training=True)
        d_loss = loss_fn(tf.ones_like(real_logits), real_logits) + 
                 loss_fn(tf.zeros_like(fake_logits), fake_logits)
    d_grads = tape.gradient(d_loss, discriminator.trainable_variables)
    d_optimizer.apply_gradients(zip(d_grads, discriminator.trainable_variables))

    # Update generator through the discriminator's response.
    noise = tf.random.normal((batch_size_now, latent_dim))
    with tf.GradientTape() as tape:
        generated = generator(noise, training=True)
        misleading_logits = discriminator(generated, training=False)
        g_loss = loss_fn(tf.ones_like(misleading_logits), misleading_logits)
    g_grads = tape.gradient(g_loss, generator.trainable_variables)
    g_optimizer.apply_gradients(zip(g_grads, generator.trainable_variables))
    return d_loss, g_loss


for epoch in range(epochs):
    shuffled = tf.random.shuffle(real_train)
    d_losses, g_losses = [], []
    for step in range(steps_per_epoch):
        start = step * batch_size
        real_batch = shuffled[start:start + batch_size]
        d_loss, g_loss = train_step(real_batch)
        d_losses.append(float(d_loss))
        g_losses.append(float(g_loss))

    print(
        f"Epoch {epoch + 1}/{epochs} - "
        f"d_loss: {sum(d_losses) / len(d_losses):.4f}, "
        f"g_loss: {sum(g_losses) / len(g_losses):.4f}"
    )

The batch size and epoch count above are starting values for an example, not validated recommendations for a particular sequence dataset. The loop drops any remainder smaller than a full batch because steps_per_epoch uses integer division. If the dataset contains fewer than one batch, increase its size, reduce batch_size, or implement deliberate handling for a smaller final batch. TensorFlow’s custom-loop guide explains the general gradient-tape pattern. The Keras conditional GAN example demonstrates a related custom train_step pattern for image data, not a tested 1D architecture.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Generate and inspect sequences

After training, sample latent vectors and pass them through the generator. The resulting array should have shape (number_to_generate, sequence_length, feature_count). If the real data was normalized before training, invert that transformation before interpreting values in the original units.

number_to_generate = 8
noise = tf.random.normal((number_to_generate, latent_dim))
samples = generator(noise, training=False).numpy()
print(samples.shape)  # (8, sequence_length, feature_count)

Plot generated sequences beside held-out real examples, using the same axes and units. Inspect both individual traces and the collection: look for plausible ranges, temporal patterns, repeated or nearly identical outputs, and abrupt artifacts. Do not judge success from loss values alone; a GAN can show changing losses without producing useful variety. Keep validation examples separate from training data and evaluate with checks that matter for the domain. A basic GAN does not by itself establish convergence, fidelity, or privacy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Choose adaptations based on the task

Decision Option When it fits
Sequence length Dense projection plus stride-1 convolutions Useful for a simple fixed-length baseline where the output length is known in advance.
Sequence length Upsampling or staged temporal expansion Consider when building longer sequences from a shorter representation; the architecture must still end at the real batch’s length.
Temporal context same padding Preserves length through stride-1 convolutions and allows whole-window context.
Temporal context causal padding Use when outputs must not depend on later time positions.
Training interface Explicit custom loop Makes the discriminator and generator phases visible and easy to modify.
Training interface Custom train_step with fit() Integrates a custom adversarial step with Keras’s training interface; the official example illustrates this approach for conditional image generation.

For conditional generation, such as generating a sequence for a specified class or context, provide the conditioning information to both networks in compatible forms rather than treating the example’s noise-only input as sufficient. The Keras conditional example illustrates the general principle for images; sequence-specific conditioning and architecture choices depend on the target data.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.