Master Generative AI with Python Code Examples Learn Fast

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 with Python: Master Pretrained LLMs, Vector DBs & Retrieval-Augmented Generation
Generative AI with Python: Master Pretrained LLMs, Vector DBs & Retrieval-Augmented Generation

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).

an image of a computer screen with the text general neutral fractal art
an image of a computer screen with the text general neutral fractal art

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:

an image of a computer screen with the text'generation ascii art in python '
an image of a computer screen with the text'generation ascii art in python '

pip install tensorflow numpy

Preparing the Data

Best Generative AI Resources for Beginners | Courses, Books & Tutorials
Best Generative AI Resources for Beginners | Courses, Books & Tutorials

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

Python Generators and Iterators Explained: Lazy Evaluation with yield
Python Generators and Iterators Explained: Lazy Evaluation with yield

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

Unlock the Power of Creativity with Generative AI 101: The Ultimate Beginner's Guide to Machine Lear
Unlock the Power of Creativity with Generative AI 101: The Ultimate Beginner's Guide to Machine Lear

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

Compiling and Training the Model

Create Stunning Mandala Art with Python Turtle (Free Code Pack!)
Create Stunning Mandala Art with Python Turtle (Free Code Pack!)
10 Python Libraries for Generative AI
10 Python Libraries for Generative AI
Simple Python code for snake game with images
Simple Python code for snake game with images
Brand Marketing Strategy, Artificial Neural Network, Digital Data, Python Programming, Big Data, Brand Marketing, Data Science, Python, Programming
Brand Marketing Strategy, Artificial Neural Network, Digital Data, Python Programming, Big Data, Brand Marketing, Data Science, Python, Programming
Generative AI on LinkedIn: #buildwithai #ai #generativeai #techskills #cybersecurity #python | 14 comments
Generative AI on LinkedIn: #buildwithai #ai #generativeai #techskills #cybersecurity #python | 14 comments
Python Cheat Sheet for Beginners
Python Cheat Sheet for Beginners
Top Greedy Algorithm Problems with Easy Python Code
Top Greedy Algorithm Problems with Easy Python Code
a computer screen with an image of a flower in the center and text that reads, colorful flowers in python
a computer screen with an image of a flower in the center and text that reads, colorful flowers in python
an image of a computer screen with the text'all neural art generator '
an image of a computer screen with the text'all neural art generator '
the cover of capabilities and capabilities for generating an image with caption in orange text
the cover of capabilities and capabilities for generating an image with caption in orange text
All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)
Emojis in python
Emojis in python
an image of a computer screen with the text'all avatar generator using python '
an image of a computer screen with the text'all avatar generator using python '
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables
Python 404
Python 404
The Ultimate Python Guide After 100 Days of Learning 🚀
The Ultimate Python Guide After 100 Days of Learning 🚀
AI Projects You Can Build With Python 🤖🐍
AI Projects You Can Build With Python 🤖🐍
Python generator expressions cheat sheet #programming #tutorial #python
Python generator expressions cheat sheet #programming #tutorial #python
a black poster with the words'60 gen project ideas '
a black poster with the words'60 gen project ideas '

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) ```

Related Articles

Xgboost Python Code Example Gui For Python Code Python Example Json File Python Send Email Code How To Add Two Numbers Together Python Python Example Quiz Crewai Sample Code Python Histogram From Dataframe Column Sample Datasets For Analysis Sample R Code