"Synthetic data generation using large language models (LLMs) offers a powerful solution to a commonly faced problem: the availability of high-quality, diverse, and privacy-compliant data. This could be used in a number of scenarios such as training a data science machine learning model (SVMs, decision trees, KNN's), finetuning a different GPT model on the data, as a solution to the coldstart problem, helping build compelling demos/apps with realistic data, scenario testing etc.\n",
"\n",
"There are a number of key drivers which may see you wanting to leverage synthetic data. \n",
"1. Human data may have privacy restrictions and/or identifiable data within it which we do not want to be used. \n",
"2. Synthetic data can be much more structured and therefore easier to manipulate than real data. \n",
"3. In domains where data is sparse or data of certain categories is sparse we may want to augment the data. \n",
"4. When dealing with imbalanced datasets or datasets which lack diversity, we may want to create data to improve the richness of our datasets.\n",
"\n",
"Unlike traditional data augmentation or manual data creation methods, using LLMs allows for the generation of rich, nuanced, and contextually relevant datasets that can significantly enhance it's usefulness to enterprises and developers.\n",
"\n",
"We split this tutorial into 2 parts. In this cookbook, we will have the following agenda:\n",
"1. CSV with a structured prompt\n",
"2. CSV with a Python program\n",
"3. Multitable CSV with a python program\n",
"4. Simply creating textual data\n",
"5. Dealing with imbalanced or non-diverse textual data\n",
"while in part 2, we will look at prompting strategies for getting better textual data.\n",
"\n",
"The last two in particular are useful for creating synthetic data to finetune another GPT model. For example using higher quality data produced by `gpt-4o` to finetune the cheaper and quicker `gpt-3.5-turbo` for improved performance while reducing costs.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NE9Rr29zlRsA"
},
"source": [
"### Getting setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YGncxYrgQ8eb"
},
"outputs": [],
"source": [
"%pip install openai\n",
"%pip install pandas\n",
"%pip install scikit-learn\n",
"%pip install matplotlib"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "8pzwvE-YQPtU"
},
"outputs": [],
"source": [
"from openai import OpenAI\n",
"import os\n",
"import re\n",
"import numpy as np\n",
"import pandas as pd\n",
"from sklearn.cluster import KMeans\n",
"import matplotlib.pyplot as plt\n",
"import json\n",
"import matplotlib\n",
"\n",
"client = OpenAI(api_key=os.environ.get(\"OPENAI_API_KEY\", \"<your OpenAI API key if not set as env var>\"))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "B8eAx4-JxaZB"
},
"source": [
"### 1. CSV with a structure prompt\n",
"Here we create data in the simplest way. You can quickly generate data by addressing 3 key points: telling it the format of the data (CSV), the schema, and useful information regarding how columns relate (the LLM will be able to deduce this from the column names but a helping hand will improve performance)."
"Create a CSV file with 10 rows of housing data.\n",
"Each row should include the following fields:\n",
" - id (incrementing integer starting at 1)\n",
" - house size (m^2)\n",
" - house price\n",
" - location\n",
" - number of bedrooms\n",
"\n",
"Make sure that the numbers make sense (i.e. more rooms is usually bigger size, more expensive locations increase price. more size is usually higher price etc. make sure all the numbers make sense). Also only respond with the CSV.\n",
"\"\"\"\n",
"\n",
"response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
" {\"role\": \"user\", \"content\": question}\n",
" ]\n",
")\n",
"res = response.choices[0].message.content\n",
"print(res)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6ym0NiIyxiVj"
},
"source": [
"### 2. CSV with a Python program\n",
"The issue with generating data directly is we are limited in the amount of data we can generate because of the context. Instead what we can do is ask the LLM to generate a python program to generate the synthetic data. This allows us to scale to much more data while also providing us a view into how the data was generated by inspecting the python program.\n",
"\n",
"This would then let us edit the python program as we desire while giving us a good basis to start from.\n"
"Certainly! Below is a Python program that generates synthetic housing data according to your specifications. We will create a pandas DataFrame with the defined fields and characteristics.\n",
"\n",
"```python\n",
"import pandas as pd\n",
"import random\n",
"\n",
"def generate_housing_data(num_rows):\n",
" data = []\n",
" \n",
" locations = [\n",
" ('City Center', 10000, 150), # (location name, base price per m², base size)\n",
"- The `generate_housing_data` function creates synthetic housing data for a specified number of rows (`num_rows`).\n",
"- We define different locations with corresponding base prices per square meter and average house sizes.\n",
"- For each house, we randomly select a location, number of bedrooms, and calculate house size and price to ensure a sensible correlation between the values.\n",
"- Finally, we create a pandas DataFrame from the generated data and return it.\n",
"\n",
"You can run this program in your Python environment, and it will output a DataFrame containing 100 rows of synthetic housing data.\n"
]
}
],
"source": [
"question = \"\"\"\n",
"Create a Python program to generate 100 rows of housing data.\n",
"I want you to at the end of it output a pandas dataframe with 100 rows of data.\n",
"Each row should include the following fields:\n",
" - id (incrementing integer starting at 1)\n",
" - house size (m^2)\n",
" - house price\n",
" - location\n",
" - number of bedrooms\n",
"\n",
"Make sure that the numbers make sense (i.e. more rooms is usually bigger size, more expensive locations increase price. more size is usually higher price etc. make sure all the numbers make sense).\n",
"\"\"\"\n",
"\n",
"response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
" {\"role\": \"user\", \"content\": question}\n",
" ]\n",
")\n",
"res = response.choices[0].message.content\n",
"print(res)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We need to make sure to parse the output of this appropriately as often there may be surrounding text to the python code. We can also explicitly ask it to state all assumptions it made about the data it's generating, however in this circumstance it told us that automatically."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HZaJs7q8xm3L"
},
"source": [
"### 3. Multitable CSV with a python program\n",
"For more complex relationships however we need to make sure to specify a few more characteristics. \n",
"\n",
"To create multiple different datasets which relate to each other (for example housing, location, house type), as before we would need to specify the format, schema and useful information. However, the useful information required to get good performance is higher now. It's case-specific but a good amount of things to describe would be how the datasets relate to each other, addressing the size of the datasets in relation to one another, making sure foreign and primary keys are made appropriately and ideally using previously generated datasets to populate new ones so the actual data values match where necessary."
"Certainly! Below is a Python program that generates the three specified pandas DataFrames for housing data, location data, and house types. Each DataFrame will include the necessary fields, and the foreign keys will ensure proper relationships among them.\n",
"print(f\"Shapes: \\nLocation: {location_df.shape}, House Types: {house_type_df.shape}, Housing: {housing_df.shape}\")\n",
"```\n",
"\n",
"### Explanation of the Code:\n",
"1. **Location DataFrame:** \n",
" - Generates random locations with attributes such as country, city, population, and area.\n",
" \n",
"2. **House Types DataFrame:** \n",
" - Generates different types of houses along with average prices and quantity available.\n",
" \n",
"3. **Housing DataFrame:** \n",
" - Generates housing data with increments on price based on house size, location, and house type, while also ensuring foreign keys (IDs) for location and house type.\n",
"\n",
"### Output:\n",
"The three DataFrames generated will logically relate to one another with consistent data types and primary–foreign key relationships, resulting in a coherent representation of the housing dataset. The output displays heads of each DataFrame and their shapes for verification.\n"
]
}
],
"source": [
"question = \"\"\"\n",
"Create a Python program to generate 3 different pandas dataframes.\n",
"\n",
"1. Housing data\n",
"I want 100 rows. Each row should include the following fields:\n",
" - id (incrementing integer starting at 1)\n",
" - house size (m^2)\n",
" - house price\n",
" - location\n",
" - number of bedrooms\n",
" - house type\n",
" + any relevant foreign keys\n",
"\n",
"2. Location\n",
"Each row should include the following fields:\n",
" - id (incrementing integer starting at 1)\n",
" - country\n",
" - city\n",
" - population\n",
" - area (m^2)\n",
" + any relevant foreign keys\n",
"\n",
" 3. House types\n",
" - id (incrementing integer starting at 1)\n",
" - house type\n",
" - average house type price\n",
" - number of houses\n",
" + any relevant foreign keys\n",
"\n",
"Make sure that the numbers make sense (i.e. more rooms is usually bigger size, more expensive locations increase price. more size is usually higher price etc. make sure all the numbers make sense).\n",
"Make sure that the dataframe generally follow common sense checks, e.g. the size of the dataframes make sense in comparison with one another.\n",
"Make sure the foreign keys match up and you can use previously generated dataframes when creating each consecutive dataframes.\n",
"You can use the previously generated dataframe to generate the next dataframe.\n",
"\"\"\"\n",
"\n",
"response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
" {\"role\": \"user\", \"content\": question}\n",
" ]\n",
")\n",
"res = response.choices[0].message.content\n",
"print(res)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Yv9XlRtauZYZ"
},
"source": [
"### 4. Simply creating textual data\n",
"Here we take a first look at creating textual data. This can be used to finetune another GPT model for example. In this case we imagine ourselves a retailer trying to streamline the process of creating descriptions for items they are selling. We again need to specify the format of the data, in particular in this case we want one which is easy to parse as an output."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The example we consider below is one in which we want to create input output training pairs for GPT model to finetune on. We will have the products' name and the category it belongs to as input and the output will be a description. \n",
"\n",
"Specifying the structure of the output explicitly and giving commands to not deviate from this help enforce the output structure. You can run this in a loop and append the data to generate more synthetic data. Again, as before we will need to parse the data well so that our code further downstream does not break."
"Input: Wireless Bluetooth Headphones, Electronics\n",
"Output: Immerse yourself in high-quality sound with these Wireless Bluetooth Headphones, featuring active noise cancellation and a comfortable over-ear design for extended listening sessions.\n",
"\n",
"2.\n",
"Input: Organic Green Tea, Beverages\n",
"Output: Enjoy a refreshing cup of Organic Green Tea, sourced from the finest leaves, packed with antioxidants, and perfect for a healthy, invigorating boost anytime.\n",
"Output: Cut with precision and ease using this Stainless Steel Kitchen Knife, designed with an ergonomic handle and a sharp blade for all your culinary tasks.\n",
"\n",
"4.\n",
"Input: Hiking Backpack, Outdoor Gear\n",
"Output: Explore the great outdoors with this durable Hiking Backpack, featuring multiple compartments for optimal organization and a breathable design for ultimate comfort on long treks.\n",
"\n",
"5.\n",
"Input: Air Fryer, Kitchen Appliances\n",
"Output: Cook your favorite meals with less oil using this Air Fryer\n"
]
}
],
"source": [
"output_string = \"\"\n",
"for i in range(3):\n",
" question = f\"\"\"\n",
" I am creating input output training pairs to fine tune my gpt model. The usecase is a retailer generating a description for a product from a product catalogue. I want the input to be product name and category (to which the product belongs to) and output to be description.\n",
" The format should be of the form:\n",
" 1.\n",
" Input: product_name, category\n",
" Output: description\n",
" 2.\n",
" Input: product_name, category\n",
" Output: description\n",
"\n",
" Do not add any extra characters around that formatting as it will make the output parsing break.\n",
" Create as many training pairs as possible.\n",
" \"\"\"\n",
"\n",
" response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
"Note: the above output is truncated. And now we can parse it as below to get a list of products, categories and their descriptions. For example, let's take a look at the products it's generated."
"### 5. Dealing with imbalanced or non-diverse textual data\n",
"Some of the most important aspects of generating high-quality synthetic data are accuracy (does the data make sense), consistency (are two separate data points for the same input roughly the same) and diversity (making sure our data distribution matches as much of the distribution that exists in production).\n",
"\n",
"\n",
"To increase the diversity of our data, we start first by clustering the data. This will provide us information about which clusters are underrepresented (imbalanced dataset) or which data is not addressed at all (widening the data distribution). Then, we will either suggest new clusters (using self-reflection type call from GPT) or ask the next iteration of our synthetic generation calls to explicitly target the underrepresented clusters. \n",
"\n",
"We can then recursively run this generation and analysis of cluster loop to automate generating diverse synthetic data."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ubdPEFYR-myU"
},
"source": [
"For demonstrative purposes, we explicitly prompt the LLM to generate information about 4 different topical areas: vehicle, clothing, toiletries, food. We will then cluster the data and see if it managed to find these 4 topic areas."
"Output: \"The Tesla Model 3 is a revolutionary electric car with impressive range and cutting-edge technology, designed to provide an exhilarating driving experience while minimizing environmental impact.\"\n",
"\n",
"2. clothing \n",
"Input: \"Nike Air Max, Shoes\" \n",
"Output: \"Elevate your sneaker game with Nike Air Max. Combining iconic style with superior comfort and support, these shoes are perfect for both workouts and casual outings.\"\n",
"\n",
"3. toiletries \n",
"Input: \"Oral-B Pro 1000, Electronic Toothbrush\" \n",
"Output: \"Achieve a superior clean with the Oral-B Pro 1000. This electronic toothbrush features 3D cleaning action that pulsates and oscillates to remove more plaque than a regular manual toothbrush.\"\n",
"\n",
"4. food \n",
"Input: \"Chobani Greek Yogurt, Yogurt\" \n",
"Output: \"Indulge in a nutritious snack with Chobani Greek Yogurt. Packed with protein and delicious flavors, it’s the perfect choice for a healthy breakfast or a satisfying treat anytime.\"\n",
"\n",
"5. vehicle \n",
"\n"
]
}
],
"source": [
"output_string = \"\"\n",
"for i in range(3):\n",
" question = f\"\"\"\n",
" I am creating input output training pairs to fine tune my gpt model. I want the input to be product name and category and output to be description. the category should be things like: mobile phones, shoes, headphones, laptop, electronic toothbrush, etc. and also more importantly the categories should come under 4 main topics: vehicle, clothing, toiletries, food)\n",
" After the number of each example also state the topic area. The format should be of the form:\n",
" 1. topic_area\n",
" Input: product_name, category\n",
" Output: description\n",
"\n",
" Do not add any extra characters around that formatting as it will make the output parsing break.\n",
"\n",
" Here are some helpful examples so you get the style of output correct.\n",
"\n",
" 1) clothing\n",
" Input: \"Shoe Name, Shoes\"\n",
" Output: \"Experience unparalleled comfort. These shoes feature a blend of modern style and the traditional superior cushioning, perfect for those always on the move.\"\n",
" \"\"\"\n",
"\n",
" response = client.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
"Note: The above output is truncated. In the example above, we would explicitly include the topic area as part of the response per example as it helps condition the proceeding output and tends to give better performance. We can also give it an actual example of what the output should look like so it gets the right idea of style of output but also to help enforce structure."
"We will now cluster the data to analyze it. We will use K-means clustering to segregate the data. An important parameter of K-means to set is K, the number of clusters.\n",
"\n",
"We know that there should be 4 cluster (4 topics) since we specified this in prompt: vehicle, electronics, clothing, food. However in general for our data, we do not know the number of clusters that exist. Therefore we will use the elbow method to find the optimal number of clusters.\n",
"\n",
"In the elbow method, we iterate through a range of different K's, each time storing the inertia. The inertia measures the sum of the squared distances between each point in a cluster and the centroid of that cluster thus telling us how well-separated and dense each cluster is. If we plot K against the inertia, we are able to see how the inertia drops and where the drop in inertia is least rapid (often making an elbow shape) we can set our optimal number of clusters. You can read into more depth about the elbow method [here](https://en.wikipedia.org/wiki/Elbow_method_(clustering))."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1BxwPTkpGzu8"
},
"source": [
"First let's store our data into a pandas dataframe for ease of analysis\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"id": "XcPBzORtKWv6"
},
"outputs": [],
"source": [
"data = {\n",
" 'Product': products,\n",
" 'Category': categories,\n",
" 'Description': descriptions\n",
"}\n",
"\n",
"df = pd.DataFrame(data)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HQbg6r37KjG0"
},
"source": [
"Next let us embed our data as the embeddings is what we will cluster since they should be close to each other in vector space if they are similar."
"This will output a chart for us in which we have to visually tell where the optimal cluster point is. We can see below that we see a gradual decrease of inertia rather than a sharp elbow but the point of steepest decrease appears to occur around 3, 4 or 5 clusters which lines up with our expectations given our prompt. "
"plt.title('Elbow Method to Determine Optimal Number of Clusters')\n",
"plt.xlabel('Number of Clusters')\n",
"plt.ylabel('Inertia')\n",
"plt.xticks(range_of_clusters)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NN7NbTmiLe_-"
},
"source": [
"For demonstration purposes we will pick 5 as the optimal cluster number to show it doesn't matter exactly where we pick it as long as we are approximately right. There are numerous correct ways to categorize data. We also store which cluster each data point belongs to."
"We will analyze the cluster data now. There are two separate things we will look to address. 1. imbalanced data, 2. Expanding the data distribution."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zaQ_mdhpOJqs"
},
"source": [
"First for imbalanced data we count the number of examples in each cluster. Then we select a few examples from each cluster at random and ask the LLM what topics these map to. "
" I previously generated some examples of input output trainings pairs and then I clustered them based on category. From each cluster I picked 3 example data point which you can find below.\n",
" I want you identify the broad topic areas these clusters belong to.\n",
" Previous examples:\n",
" {formatted_examples}\n",
"\n",
"\n",
" Your output should be strictly of the format:\n",
" Cluster: number, topic: topic\n",
" Cluster: number, topic: topic\n",
" Cluster: number, topic: topic\n",
"\n",
" Do not add any extra characters around that formatting as it will make the output parsing break.\n",
" \"\"\"\n",
"\n",
"response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed analyze clustered data\"},\n",
"clusters = [{\"cluster\": int(cluster), \"topic\": topic} for cluster, topic in matches]\n",
"json_output = json.dumps(clusters, indent=2)\n",
"print(json_output)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "x5hszl-SZVdi"
},
"source": [
"We now have the clusters and their counts so we could prompt the LLM to generate more examples within the topics we want. However for this example we won't take that further as they are well-split and you would just follow the procedure above for prompting the model to generate data while passing in the underrepresented topics."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yVD_TPsHYvDb"
},
"source": [
"Next, we will try and deal with increasing the diversity of our data distribution. \n",
"\n",
"First we start in a similar way by finding a few examples from each cluster at random and ask the LLM what topics these map to. In addition to this in the same LLM call, we will ask it to generate more topics to increase the diversity of our data. We do this in one call to save time/cost."
" I previously generated some examples of input output trainings pairs and then I clustered them based on category. From each cluster I picked 3 example data point which you can find below.\n",
" I want to promote diversity in my examples across categories so follow the procedure below:\n",
" 1. You must identify the broad topic areas these clusters belong to.\n",
" 2. You should generate further topic areas which don't exist so I can generate data within these topics to improve diversity.\n",
"\n",
"\n",
" Previous examples:\n",
" {formatted_examples}\n",
"\n",
"\n",
" Your output should be strictly of the format:\n",
"\n",
" 1. Cluster topic mapping\n",
" Cluster: number, topic: topic\n",
" Cluster: number, topic: topic\n",
" Cluster: number, topic: topic\n",
"\n",
" 2. New topics\n",
" 1. topic\n",
" 2. topic\n",
" 3. topic\n",
" 4. topic\n",
"\n",
" Do not add any extra characters around that formatting as it will make the output parsing break. It is very important you stick to that output format\n",
" \"\"\"\n",
"\n",
"response = client.chat.completions.create(\n",
" model=datagen_model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to analyze clustered data\"},\n",
"We can see here again that we explicitly prompt the output structure it should follow. I also tell it the purpose of generating topics (to promote diversity) so the model has full context."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "s254oJ-Ecka0"
},
"source": [
"We then parse the data into a list of cluster-mapping jsons and a list of topics"
"cluster_topic_mapping_lines = cluster_mapping_part.split(\"\\n\")[1:] # Skip the first two lines\n",
"cluster_topic_mapping = [{\"cluster\": int(line.split(\",\")[0].split(\":\")[1].strip()), \"topic\": line.split(\":\")[2].strip()} for line in cluster_topic_mapping_lines]\n",
"\n",
"# Parse new topics\n",
"new_topics_lines = new_topics_part.split(\"\\n\")[1:] # Skip the first line\n",
"new_topics = [line.split(\". \")[1] for line in new_topics_lines]\n",
"\n",
"cluster_topic_mapping, new_topics"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CX26-PGdcui0"
},
"source": [
"And finally we can use this information to further prompt a model to keep generating synthetic data. We do this by passing all the topics in the list of jsons to the prompt below."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"id": "zHf4LnVk0aHw"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1. Automotive \n",
"Input: \"Tesla Model S, Electric Vehicles\" \n",
"Output: \"The Tesla Model S delivers exhilarating performance with advanced electric technology, offering a sleek design, impressive range, and an industry-leading infotainment system.\"\n",
"\n",
"2. Personal Care \n",
"Input: \"Oral-B Pro 1000, Electronic Toothbrush\" \n",
"Output: \"The Oral-B Pro 1000 features a 3D cleaning action that oscillates, rotates, and pulsates to remove plaque, ensuring a deeper clean for healthier gums.\"\n",
"\n",
"3. Footwear \n",
"Input: \"Nike Air Max 270, Shoes\" \n",
"Output: \"Step into comfort and style with Nike Air Max 270, designed with a large Max Air unit for superior cushioning and a breathable upper for a snug fit.\"\n",
"\n",
"4. Electronics \n",
"Input: \"Apple iPhone 12, Mobile Phones\" \n",
"Output: \"The Apple iPhone 12 combines powerful performance with stunning design, equipped with A14 Bionic chip and advanced camera systems for capturing every moment in stunning detail.\"\n",
"\n",
"5. Food \n",
"Input: \"Nature Valley Granola Bars, Snacks\" \n",
"Output: \"Nature Valley Granola Bars offer a wholesome crunch made from simple, delicious ingredients, providing a perfect snack that fuels your adventure.\"\n",
"\n",
"6. Automotive \n",
"Input: \"Ford F-150, Electric Vehicles\" \n",
"Output: \"The Ford F-150 stands at the forefront of durability and innovation, with its powerful electric version setting new standards for strength and sustainability in the truck category.\" \n",
"Output: \"Philips Sonicare delivers superior cleaning with dynamic technology that provides up to 31,000 strokes per minute for a healthier mouth and brighter smile.\"\n",
"\n",
"8. Footwear \n",
"Input: \"Adidas Ultraboost, Shoes\" \n",
"Output: \"The Adidas Ultraboost is a game-changer in running footwear, featuring responsive cushioning and a knit upper for a snug, supportive fit that adapts to any run.\"\n",
"\n",
"9. Electronics \n",
"Input: \"Dell XPS 13, Laptop\" \n",
"Output: \"The Dell XPS 13 is a remarkable laptop with an ultra-thin design, featuring a stunning InfinityEdge display and powerful performance to accommodate your multitasking needs.\"\n",
"Output: \"Kraft Macaroni & Cheese offers quick and convenient comfort food, combining creamy cheese sauce with perfectly cooked pasta for a simple meal that satisfies.\"\n",
"\n",
"1. Automotive \n",
"Input: \"Toyota Camry, Mobile Phones\" \n",
"Output: \"The Toyota Camry is a midsize sedan that combines efficiency with modern technology. It offers a spacious interior and the latest features for an enjoyable driving experience.\"\n",
"\n",
"2. Personal Care \n",
"Input: \"Oral-B Pro 1000, Electronic Toothbrush\" \n",
"Output: \"The Oral-B Pro 1000 not only provides powerful cleaning action but also enhances your oral hygiene routine with its smart pressure sensor and various cleaning modes.\"\n",
"\n",
"3. Footwear \n",
"Input: \"Nike Air Max, Shoes\" \n",
"Output: \"Step into comfort with the Nike Air Max. With cutting-edge technology and a sleek design, these shoes are perfect for athletes and casual wearers alike.\"\n",
"\n",
"4. Food \n",
"Input: \"Nature's Valley Granola Bar, Food\" \n",
"Output: \"Savor the wholesome goodness of Nature's Valley Granola Bar, crafted with real ingredients to fuel your day with delicious flavor and crunchy satisfaction.\"\n",
"\n",
"5. Electric Vehicles \n",
"Input: \"Tesla Model 3, Mobile Phones\" \n",
"Output: \"The Tesla Model 3 is a revolutionary electric vehicle that combines performance with sustainability, featuring an intuitive interface and cutting-edge technology for an exceptional driving experience.\"\n",
"\n",
"1. Automotive \n",
"Input: \"Tesla Model 3, Electric Vehicles\" \n",
"Output: \"The Tesla Model 3 combines cutting-edge technology with eco-friendly driving. Enjoy a sleek design, impressive range, and top-notch safety features, making it the perfect electric car for the modern driver.\"\n",
"\n",
"2. Personal Care \n",
"Input: \"Oral-B Pro 1000, Electronic Toothbrush\" \n",
"Output: \"Achieve a superior clean with the Oral-B Pro 1000. Featuring advanced 3D cleaning action, this electronic toothbrush ensures effective plaque removal while being gentle on gums, allowing you to maintain optimum oral health.\"\n",
"\n",
"3. Footwear \n",
"Input: \"Nike Air Max, Shoes\" \n",
"Output: \"Step up your game with Nike Air Max shoes. Combining iconic cushioning technology and bold style, these shoes provide ultimate comfort and support, perfect for both casual wear and athletic performance.\"\n",
"\n",
"4. Food \n",
"Input: \"Oreo Cookies, Snacks\" \n",
"Output: \"Indulge in the classic taste of Oreo Cookies. With their irresistible cream filling sandwiched between two crunchy chocolate wafers, these treats are perfect for satisfying your sweet tooth any time of the day.\"\n",
"\n",
"5. Personal Care \n",
"Input: \"Garnier Micellar Water, Skincare\" \n",
"Output: \"Garnier Micellar Water gently removes makeup and impurities while hydrating the skin. This soothing formula is suitable for all skin types, making it a must-have in your daily skincare routine.\"\n",
"\n",
"6. Automotive \n",
"Input: \"Ford F-150, Trucks\" \n",
"Output: \"The Ford F-150 is the quintessential pickup truck, combining power, reliability, and innovative technology. Equipped with advanced towing capabilities and a spacious interior, it's designed for both work and play.\"\n",
"\n",
"7. Electronics \n",
"Input: \"Samsung Galaxy S21, Mobile Phones\" \n",
"Output: \"Experience the future of mobile technology with the Samsung Galaxy S21. This smartphone features a stunning display, powerful processor, and multiple camera options, perfect for capturing life's moments in high definition.\"\n",
"\n",
"8. Footwear \n",
"Input: \"Adidas Ultraboost, Shoes\" \n",
"Output: \"Run in style with Adidas Ultraboost shoes. Known for their comfort and performance, these shoes utilize responsive cushioning to provide unmatched energy return with every step you take.\" \n",
"\n",
"9. Electronics \n",
"Input: \"Dell XPS 13, Laptops\" \n",
"Output: \"The Dell XPS 13 redefines the laptop experience with its stunning InfinityEdge display, powerful performance, and sleek design. Ideal for both professionals and students looking for portability and functionality.\"\n",
"Output: \"Philips Sonicare's electronic toothbrush guarantees a superior cleaning experience with its advanced sonic technology. This toothbrush not only helps remove plaque but also promotes healthier gums for a brighter smile.\"\n",
" I am creating input output training pairs to fine tune my gpt model. I want the input to be product name and category and output to be description. the category should be things like: mobile phones, shoes, headphones, laptop, electronic toothbrush, etc. and also more importantly the categories should come under some main topics: {[entry['topic'] for entry in cluster_topic_mapping]})\n",
" After the number of each example also state the topic area. The format should be of the form:\n",
" 1. topic_area\n",
" Input: product_name, category\n",
" Output: description\n",
"\n",
" Do not add any extra characters around that formatting as it will make the output parsing break.\n",
"\n",
" Here are some helpful examples so you get the style of output correct.\n",
"\n",
" 1) clothing\n",
" Input: \"Shoe Name, Shoes\"\n",
" Output: \"Experience unparalleled comfort. These shoes feature a blend of modern style and the traditional superior cushioning, perfect for those always on the move.\"\n",
" \"\"\"\n",
"\n",
" response = client.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant designed to generate synthetic data.\"},\n",
" {\"role\": \"user\", \"content\": question}\n",
" ]\n",
" )\n",
" res = response.choices[0].message.content\n",
" output_string += res + \"\\n\" + \"\\n\"\n",
"print(output_string)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RQMHQxnZdRug"
},
"source": [
"You can run this in a loop to append to your previous data and in this way you can keep generating more textual synthetic data to train another GPT model while making sure that we cater to imbalanced datasets and generating a diversity of data."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Hiim8Xg5djGH"
},
"source": [
"You have now completed part 1 of the synthetic data generation tutorial where we have gone through:\n",
"* CSV with a structured prompt\n",
"* CSV with a Python program\n",
"* Multitable CSV with a python program\n",
"* Simply creating textual data\n",
"* Dealing with imbalanced or non-diverse textual data\n",
"\n",
"In part 2 you will find find out techniques for better prompting an LLM to enhance textual synthetic data generation."