About
wHAT IS IT?
Generative AI refers to a category of artificial intelligence (AI) that involves the creation of new content, data, or outputs that mimic human-like creativity or decision-making.
Unlike traditional AI systems that are task-specific and rule-based, generative AI has the ability to generate novel and diverse outputs based on patterns and information it has learned from training data.
Can you believe that all images on this page are generated through AI? Isn’t that cool!
Code for image generator
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
# Define the generator model
def build_generator(latent_dim): model = tf.keras.Sequential()
model.add(layers.Dense(128, input_dim=latent_dim, activation=‘relu’))
model.add(layers.Dense(784, activation=‘sigmoid’))
model.add(layers.Reshape((28, 28, 1)))
return model
# Define the discriminator model
def build_discriminator(img_shape):
model = tf.keras.Sequential()
model.add(layers.Flatten(input_shape=img_shape))
model.add(layers.Dense(128, activation=‘relu’))
model.add(layers.Dense(1, activation=‘sigmoid’))
return model
# Define the GAN model
def build_gan(generator, discriminator):
discriminator.trainable = False model = tf.keras.Sequential()
model.add(generator)
model.add(discriminator)
return model
# Load and preprocess the dataset (MNIST as an example) (x_train, _), (_, _) = tf.keras.datasets.mnist.load_data()
x_train = x_train / 127.5 – 1.0
x_train = np.expand_dims(x_train, axis=-1)
# Set hyperparameters
latent_dim = 100 img_shape = (28, 28, 1)
# Build and compile the models generator = build_generator(latent_dim)
discriminator = build_discriminator(img_shape)
discriminator.compile(loss=‘binary_crossentropy’,
optimizer=‘adam’, metrics=[‘accuracy’])
discriminator.trainable = False
gan = build_gan(generator, discriminator)
gan.compile(loss=‘binary_crossentropy’, optimizer=‘adam’)
# Training loop
epochs = 10000
batch_size = 64
half_batch = batch_size // 2
for epoch in range(epochs):
idx = np.random.randint(0, x_train.shape[0], half_batch)
imgs = x_train[idx]
noise = np.random.normal(0, 1, (half_batch, latent_dim))
gen_imgs = generator.predict(noise)
d_loss_real = discriminator.train_on_batch(imgs, np.ones((half_batch, 1)))
d_loss_fake = discriminator.train_on_batch(gen_imgs, np.zeros((half_batch, 1)))
d_loss = 0.5* np.add(d_loss_real, d_loss_fake)
noise = np.random.normal(0, 1, (batch_size, latent_dim))
valid_y = np.array([1] * batch_size)
g_loss = gan.train_on_batch(noise, valid_y)
if epoch % 100 == 0:
print(f”Epoch {epoch}, D Loss: {d_loss[0]}, G Loss: {g_loss}“)
# Save generated images at specific intervals
if epoch % 1000 == 0:
gen_imgs = 0.5 * gen_imgs + 0.5 # Rescale to [0, 1]
fig, axs = plt.subplots(5, 5)
count = 0
for i in range(5):
for j in range(5):
axs[i, j].imshow(gen_imgs[count, :, :, 0], cmap=‘gray’)
axs[i, j].axis(‘off’) count += 1 plt.show()
Code for text generator
from transformers import GPT2LMHeadModel, GPT2Tokenizer
def chatbot(prompt, model, tokenizer, max_length=50, temperature=0.7, top_k=50): input_ids = tokenizer.encode(prompt, return_tensors=‘pt’) # Generate a response output = model.generate( input_ids, max_length=max_length,
temperature=temperature, top_k=top_k,
pad_token_id=tokenizer.eos_token_id )
# Decode and return the generated response response = tokenizer.decode(output[0], skip_special_tokens=True)
return response # Load pre-trained GPT-2 model and tokenizer model_name = “gpt2” model = GPT2LMHeadModel.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
# Chat with the model while True: user_input = input(“You: “) # Exit the loop if the user types ‘exit’ if user_input.lower() == ‘exit’: break response = chatbot(user_input, model, tokenizer)
print(“ChatGPT: “ + response)