Generative AI has emerged as a powerful tool in the realm of machine learning, enabling the creation of new, synthetic yet realistic data. Python, with its rich ecosystem of libraries and frameworks, is a go-to language for implementing generative AI models. Let's delve into an example of creating a simple generative AI code in Python using the TensorFlow library.

Generative AI models, such as Generative Adversarial Networks (GANs), seq2seq models, and transformers, have applications ranging from image and music generation to text synthesis. In this example, we'll explore how to build a simple character-level language model using a Recurrent Neural Network (RNN).

Setting up the Environment
Before we dive into the code, ensure that you have Python 3.6 or later installed. Also, install the required libraries by running:

pip install tensorflow numpy
Preparing the Data

For this example, we'll use a dataset containing nursery rhymes. The data is already preprocessed, with each line consisting of lower-case characters and a newline character ('\n').
Let's load and preprocess the data:
```python import numpy as np # Load the data with open('nursery_rhymes.txt', 'r') as f: data = f.read().lower() # Create a character set and a mapping dictionary chars = sorted(list(set(data))) char_to_idx = {char: idx for idx, char in enumerate(chars)} idx_to_char = {idx: char for idx, char in enumerate(chars)} # Prepare the data for training X, y = [], [] for i in range(len(data) - 50): X.append(data[i:i+50]) y.append(data[i+50]) X = np.array([[char_to_idx[c] for c in x] for x in X]) y = np.array([[char_to_idx[c]] for c in y]) ```
Building the RNN Model

Now, let's build a simple RNN model using TensorFlow. This model will learn to predict the next character given the previous 50 characters.
```python import tensorflow as tf # Hyperparameters vocab_size = len(chars) embedding_dim = 256 rnn_units = 1024 batch_size = 32 buffer_size = 10000 sequence_length = 50 # Create the dataset dataset = tf.data.Dataset.from_tensor_slices((X, y)).shuffle(buffer_size).batch(batch_size, drop_remainder=True) # Define the model architecture model = tf.keras.models.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[None, None]), tf.keras.layers.GRU(rnn_units, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'), tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(vocab_size, activation='softmax')) ]) ```
Next, we'll compile and train the model. After that, we can use it to generate text. Stay tuned for the next section where we train the model, and explore text generation.
Training and Text Generation

Now that our model is set up, let's train it and use it for text generation.
Compiling and Training the Model



















We'll use the Adam optimizer and sparse categorical crossentropy as our loss function. Finally, we'll compile and train the model.
```python model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(dataset, epochs=10) ```
Text Generation
To generate text, we'll create a function that takes an initial string and the number of characters to generate. This function will repeatedly feed the last generated characters back into the model to generate the next character.
```python def generate_text(model, start_string, num_chars_to_generate=1000): # Number of characters to generate num_chars_to_generate = num_chars_to_generate # Converting our start string to numbers (imestamp:c) input evaluates -= [char_to_idx[s] for s in start_string] input evaluates = tf.expand_dim(input evaluates, axis=0) # Empty list to store the generated characters generated = [] # Here's where the magic happens! for _ in range(num_chars_to_generate): # Predict the next character predictions = model(input evaluates, training=False) predictions = tf.argmax(predictions, axis=2) # Get the index of the predicted character predicted_idx = predictions[-1] # Convert the index to a character predicted_char = idx_to_char[predicted_idx] generated.append(predicted_char) # Update input evaluates for the next iteration input evaluates = tf.expand_dim([predicted_idx], axis=0) return start_string + ''.join(generated) ```