当前位置:   article > 正文

在亚马逊云科技上利用生成式AI开发用户广告营销平台

在亚马逊云科技上利用生成式AI开发用户广告营销平台

项目简介:

小李哥将继续每天介绍一个基于亚马逊云科技AWS云计算平台的全球前沿AI技术解决方案,帮助大家快速了解国际上最热门的云计算平台亚马逊云科技AWS AI最佳实践,并应用到自己的日常工作里。

本次介绍的是如何利用亚马逊云科技大模型托管服务Amazon Bedrock和个性化推荐算法服务Amazon Personalize搭建面向用户的广告营销平台,将生成式AI应用到用户的广告营销场景,提升用户产品转化率。本架构设计全部采用了云原生Serverless架构,提供可扩展和安全的AI解决方案。通过Application Load Balancer和AWS ECS将应用程序与AI模型集成。本方案的解决方案架构图如下:

方案所需基础知识 

什么是 Amazon Bedrock?

Amazon Bedrock 是亚马逊云科技提供的一项服务,旨在帮助开发者轻松构建和扩展生成式 AI 应用。Bedrock 提供了访问多种强大的基础模型(Foundation Models)的能力,支持多种不同大模型厂商的模型,如AI21 Labs, Anthropic, Cohere, Meta, Mistral AI, Stability AI, 和Amazon,用户可以使用这些模型来创建、定制和部署各种生成式 AI 应用程序,而无需从头开始训练模型。Bedrock 支持多个生成式 AI 模型,包括文本生成、图像生成、代码生成等,简化了开发流程,加速了创新。

什么是 Amazon Personalize?

Amazon Personalize 是亚马逊云科技提供的一项机器学习服务,旨在帮助开发者轻松构建和部署个性化推荐系统。该服务利用亚马逊多年来在推荐系统领域积累的经验,通过自动化机器学习模型来生成高度精准的个性化推荐,无需开发者具备深厚的机器学习背景。

应用场景

定制广告营销内容

Amazon Personalize 可以根据用户的行为和偏好,动态生成个性化的广告和营销内容,提升广告投放的效果和转化率。

产品推荐

在电商平台中,Personalize 可根据用户的浏览和购买历史,推荐相关产品,增加销售额和用户粘性。

内容推荐

在流媒体平台上,Personalize 能根据用户的观影或听歌习惯,推荐符合其兴趣的电影、电视剧或音乐,提升用户体验。

电子邮件个性化

Personalize 可以用于定制电子邮件的内容,确保每个用户接收到的邮件内容都是基于其偏好定制的,从而提高邮件的打开率和点击率。

本方案包括的内容

1. 将S3存储桶中的用户源数据导入到Amazon Personalize推荐系统

2. 利用我们的用户源数据,训练、部署一个基于源用户数据的Amazon Personalize推荐算法模型,

3. 使用基于Amazon Personalize推荐结果的提示词工程,利用Amazon Bedrock上的基础AI模型生成定制化营销邮件

项目搭建具体步骤:

1. 进入亚马逊云科技控制台,确认Titan Text G1 - Lite模型是开启的,我们将利用该模型进行广告内容生成。

2. 接下来我们打开亚马逊云科技机器学习服务SageMaker,新建一个Jupyter Notebook:“Lab-Notebook”并打开。

3. 新建一个NoteBook命名为:“personalized-marketing.ipynb”,并粘贴、运行以下代码。首先我们导入必要依赖。

  1. # Import packages
  2. import boto3
  3. import time
  4. import pandas as pd
  5. import json
  6. import random

4. 下面我们将我们的csv文件中保存的电影评分源数据导入到DataFrame中

  1. item_data = pd.read_csv('imdb/items.csv', sep=',', dtype={'PROMOTION': "string"})
  2. item_data.head(5)
  3. movies = pd.read_csv('imdb/items.csv', sep=',', usecols=[0,1], encoding='latin-1', dtype={'movieId': "str", 'imdbId': "str", 'tmdbId': "str"})
  4. pd.set_option('display.max_rows', 25)
  5. movies

5. 接下来我们为Amazon Personalize模型算法训练创建必要的前提条件,如创建Amazon Personalize客户端、获取IAM权限和S3存储桶。

  1. # Configure the SDK to Amazon Personalize
  2. personalize = boto3.client('personalize')
  3. personalize_runtime = boto3.client('personalize-runtime')
  4. account_id = boto3.client('sts').get_caller_identity().get('Account')
  5. print("account id:", account_id)
  6. with open('/opt/ml/metadata/resource-metadata.json') as notebook_info:
  7. data = json.load(notebook_info)
  8. resource_arn = data['ResourceArn']
  9. region = resource_arn.split(':')[3]
  10. print("region:", region)
  11. # Set up a Boto3 client to access IAM functions
  12. iam = boto3.client('iam')
  13. # A role has been set up for this solution. The following obtains the ARN for that role
  14. # and also prints the role name for your information
  15. role_name = iam.get_role(RoleName='personalize_exec_role')
  16. role_arn = role_name['Role']['Arn']
  17. role_name = role_arn.split('/')[1]
  18. role_name
  19. # Set up a Boto3 client to access S3 functions
  20. s3 = boto3.client('s3')
  21. # Get a list of all S3 buckets so that we can find the one that starts with "personalized-marketing"
  22. response = s3.list_buckets()
  23. # Filter buckets that start with 'personalized-marketing'
  24. buckets_list = [bucket['Name'] for bucket in response['Buckets'] if bucket['Name'].startswith('personalized-marketing')]
  25. # Get the one bucket name from the list
  26. for data_bucket in buckets_list:
  27. data_bucket_name = data_bucket
  28. # Display the name of the bucket found
  29. data_bucket_name

6. 由于Amazon Personalize模型算法训练的数据集需要放置在S3存储桶中,我们将我们的源数据上传到我们刚刚创建的S3桶。

  1. interactions_filename = 'interactions.csv'
  2. items_filename = "items.csv"
  3. interactions_file = interactions_filename
  4. try:
  5. s3.get_object(
  6. Bucket=data_bucket_name,
  7. Key=interactions_filename,
  8. )
  9. print("{} already exists in the bucket {}".format(interactions_filename, data_bucket_name))
  10. except s3.exceptions.NoSuchKey:
  11. # Uploading the file if it does not already exist
  12. boto3.Session().resource('s3').Bucket(data_bucket_name).Object(interactions_filename).upload_file(interactions_filename)
  13. print("File {} uploaded to bucket {}".format(interactions_filename, data_bucket_name))
  14. items_file = "imdb/" + items_filename
  15. try:
  16. s3.get_object(
  17. Bucket=data_bucket_name,
  18. Key=items_filename,
  19. )
  20. print("{} already exists in the bucket {}".format(items_file, data_bucket_name))
  21. except s3.exceptions.NoSuchKey:
  22. # Uploading the file if it does not already exist
  23. # Note that the following line will be needed for the DIY
  24. boto3.Session().resource('s3').Bucket(data_bucket_name).Object(items_filename).upload_file(items_file)
  25. print("File {} uploaded to bucket {}".format(items_filename, data_bucket_name))

7. 接下来我们创建用于Amazon Personalize模型算法训练的数据集组,用于隔离和区分不同的数据集。训练Amazon Personalize模型算法需要创建3个不同的数据集和数据集组,分别为用户信息数据集、推荐物品数据集以及用户购买/使用物品的历史记录的用户物品交互数据集“User-item-interactions”。

  1. marketing_dataset_group_name = "marketing-email-dataset"
  2. try:
  3. # Try to create the dataset group. This block will run fully if the dataset group does not exist yet
  4. # Refer to this section for the DIY
  5. create_dataset_group_response = personalize.create_dataset_group(
  6. name = marketing_dataset_group_name,
  7. domain='VIDEO_ON_DEMAND'
  8. )
  9. marketing_dataset_group_arn = create_dataset_group_response['datasetGroupArn']
  10. print(json.dumps(create_dataset_group_response, indent=2))
  11. print ('\nCreating the Dataset Group with dataset_group_arn = {}'.format(marketing_dataset_group_arn))
  12. except personalize.exceptions.ResourceAlreadyExistsException as e:
  13. # If the dataset group already exists, get the unique identifier, marketing_dataset_group_arn,
  14. # from the existing resource
  15. marketing_dataset_group_arn = 'arn:aws:personalize:'+region+':'+account_id+':dataset-group/'+marketing_dataset_group_name
  16. print ('\nThe the Dataset Group with dataset_group_arn = {} already exists'.format(marketing_dataset_group_arn))
  17. print ('\nWe will be using the existing Dataset Group dataset_group_arn = {}'.format(marketing_dataset_group_arn))

8.  我们以创建用户-物品交互数据集“User-item-interactions”为例。接下来我们定义一个数据集结构描述的JSON脚本,帮助Amazon Personalize 就能够理解数据的含义,并在训练推荐模型时正确地使用这些数据。

  1. interactions_schema_name = "marketing_interactions_schema"
  2. interactions_schema = {
  3. "type": "record",
  4. "name": "Interactions",
  5. "namespace": "com.amazonaws.personalize.schema",
  6. "fields": [
  7. {
  8. "name": "USER_ID",
  9. "type": "string"
  10. },
  11. {
  12. "name": "ITEM_ID",
  13. "type": "string"
  14. },
  15. {
  16. "name": "EVENT_TYPE", # "Watch", "Click", etc.
  17. "type": "string"
  18. },
  19. {
  20. "name": "TIMESTAMP",
  21. "type": "long"
  22. }
  23. ],
  24. "version": "1.0"
  25. }
  26. try:
  27. # Try to create the interactions dataset schema. This block will run fully
  28. # if the interactions dataset schema does not exist yet
  29. create_schema_response = personalize.create_schema(
  30. name = interactions_schema_name,
  31. schema = json.dumps(interactions_schema),
  32. domain='VIDEO_ON_DEMAND'
  33. )
  34. print(json.dumps(create_schema_response, indent=2))
  35. marketing_interactions_schema_arn = create_schema_response['schemaArn']
  36. print ('\nCreating the Interactions Schema with marketing_interactions_schema_arn = {}'.format(marketing_interactions_schema_arn))
  37. except personalize.exceptions.ResourceAlreadyExistsException:
  38. # If the interactions dataset schema already exists, get the unique identifier marketing_interactions_schema_arn
  39. # from the existing resource
  40. marketing_interactions_schema_arn = 'arn:aws:personalize:'+region+':'+account_id+':schema/'+interactions_schema_name
  41. print('The schema {} already exists.'.format(marketing_interactions_schema_arn))
  42. print ('\nWe will be using the existing Interactions Schema with marketing_interactions_schema_arn = {}'.format(marketing_interactions_schema_arn))

9. 接下来我们正式创建训练数据集,对于其他两个数据集我们可以按照相同的方式创建。

  1. interactions_dataset_name = "marketing_interactions"
  2. try:
  3. # Try to create the interactions dataset. This block will run fully
  4. # if the interactions dataset does not exist yet
  5. dataset_type = 'INTERACTIONS'
  6. create_dataset_response = personalize.create_dataset(
  7. name = interactions_dataset_name,
  8. datasetType = dataset_type,
  9. datasetGroupArn = marketing_dataset_group_arn,
  10. schemaArn = marketing_interactions_schema_arn
  11. )
  12. marketing_interactions_dataset_arn = create_dataset_response['datasetArn']
  13. print(json.dumps(create_dataset_response, indent=2))
  14. print ('\nCreating the Interactions Dataset with marketing_interactions_dataset_arn = {}'.format(marketing_interactions_dataset_arn))
  15. except personalize.exceptions.ResourceAlreadyExistsException:
  16. # If the interactions dataset already exists, get the unique identifier, marketing_interactions_dataset_arn,
  17. # from the existing resource
  18. marketing_interactions_dataset_arn = 'arn:aws:personalize:'+region+':'+account_id+':dataset/'+marketing_dataset_group_name+'/INTERACTIONS'
  19. print('The Interactions Dataset {} already exists.'.format(marketing_interactions_dataset_arn))
  20. print ('\nWe will be using the existing Interactions Dataset with marketing_interactions_dataset_arn = {}'.format(marketing_interactions_dataset_arn))

 10. 我们创建一个import job导入任务,将S3中的数据集导入到Amazon Personalize中的数据集,用于模型算法训练。

  1. interactions_import_job_name = "dataset_import_interaction"
  2. # Check if the import job already exists
  3. # List the import jobs
  4. interactions_dataset_import_jobs = personalize.list_dataset_import_jobs(
  5. datasetArn=marketing_interactions_dataset_arn,
  6. maxResults=100
  7. )['datasetImportJobs']
  8. # Check if there is an existing job with the prefix
  9. job_exists = False
  10. job_arn = None
  11. for job in interactions_dataset_import_jobs:
  12. if (interactions_import_job_name in job['jobName']):
  13. job_exists = True
  14. job_arn = job['datasetImportJobArn']
  15. if (job_exists):
  16. marketing_interactions_dataset_import_job_arn = job_arn
  17. print('The Interactions Import Job {} already exists.'.format(marketing_interactions_dataset_import_job_arn))
  18. print ('\nWe will be using the existing Interactions Import Job with marketing_interactions_dataset_import_job_arn = {}'.format(marketing_interactions_dataset_import_job_arn))
  19. else:
  20. # If there is no import job with the prefix, create it
  21. create_dataset_import_job_response = personalize.create_dataset_import_job(
  22. jobName = interactions_import_job_name,
  23. datasetArn = marketing_interactions_dataset_arn,
  24. dataSource = {
  25. "dataLocation": f"s3://{data_bucket_name}/interactions.csv"
  26. },
  27. roleArn = role_arn
  28. )
  29. marketing_interactions_dataset_import_job_arn = create_dataset_import_job_response['datasetImportJobArn']
  30. print(json.dumps(create_dataset_import_job_response, indent=2))
  31. print ('\nImporting the Interactions Data with marketing_interactions_dataset_import_job_arn = {}'.format(marketing_interactions_dataset_import_job_arn))

11. 我们从Amazon Personalize获取预定义的视频话题相关(VIDEO_ON_DEMAND)的推荐算法,再创建并训练一个推荐器实例为用户推荐视频,推荐器会根据用户信息和观看历史推荐他们最喜欢的视频。

  1. available_recipes = personalize.list_recipes(domain='VIDEO_ON_DEMAND')
  2. display_available_recipes = available_recipes ['recipes']
  3. available_recipes = personalize.list_recipes(domain='VIDEO_ON_DEMAND',nextToken=available_recipes['nextToken'])#paging to get the rest of the recipes
  4. display_available_recipes = display_available_recipes + available_recipes['recipes']
  5. display(display_available_recipes)
  6. recommender_top_picks_for_you_name = "marketing_top_picks_for_you"
  7. try:
  8. create_recommender_response = personalize.create_recommender(
  9. name = recommender_top_picks_for_you_name,
  10. recipeArn = 'arn:aws:personalize:::recipe/aws-vod-top-picks',
  11. datasetGroupArn = marketing_dataset_group_arn,
  12. recommenderConfig = {"enableMetadataWithRecommendations": True}
  13. )
  14. marketing_recommender_top_picks_arn = create_recommender_response["recommenderArn"]
  15. print (json.dumps(create_recommender_response))
  16. print ('\nCreating the Top Picks For You recommender with marketing_recommender_top_picks_arn = {}'.format(marketing_recommender_top_picks_arn))
  17. except personalize.exceptions.ResourceAlreadyExistsException as e:
  18. marketing_recommender_top_picks_arn = 'arn:aws:personalize:'+region+':'+account_id+':recommender/'+recommender_top_picks_for_you_name
  19. print('The Top Picks For You recommender {} already exists.'.format(marketing_recommender_top_picks_arn))
  20. print ('\nWe will be using the existing Top Picks For You recommender with marketing_recommender_top_picks_arn = {}'.format(marketing_recommender_top_picks_arn))

12. 我们定义一个函数用户为不同的用户,基于他们的id推荐出他们最喜欢的视频

  1. def getRecommendedMoviesForUserId(
  2. user_id,
  3. marketing_recommender_top_picks_arn,
  4. item_data,
  5. number_of_movies_to_recommend = 5):
  6. # For a user_id, get the top n (number_of_movies_to_recommend) movies by using Amazon Personalize
  7. # and get the additional metadata for each movie (item_id) from the item_data
  8. # Return a list of movie dictionaries (movie_list) with the relevant data
  9. # Get recommended movies
  10. get_recommendations_response = personalize_runtime.get_recommendations(
  11. recommenderArn = marketing_recommender_top_picks_arn,
  12. userId = str(user_id),
  13. numResults = number_of_movies_to_recommend,
  14. metadataColumns = {
  15. "ITEMS": ['TITLE', 'GENRES']
  16. }
  17. )
  18. # Create a list of movies with title, genres
  19. movie_list = []
  20. for recommended_movie in get_recommendations_response['itemList']:
  21. movie_list.append(
  22. {
  23. 'title' : recommended_movie['metadata']['title'],
  24. 'genres' : recommended_movie['metadata']['genres'].replace('|', ' and ')
  25. }
  26. )
  27. return movie_list

13. 下面我们就开始利用Bedrock结合我们的用户推荐结果,为用户发送广告营销邮件。在以下代码中我们定义了用户的个人信息demographic,如用户是一名50岁居住在多伦多的成年人。再从Amazon Personalize取出基于用户id获得的推荐电影,基于以上信息构建一个提示词模板,再利用Titan Text AI大模型生成广告营销邮件。

  1. # Set up a Boto3 client to access the functions within Amazon Bedrock
  2. bedrock = boto3.client('bedrock-runtime')
  3. # Model parameters
  4. # The LLM you will be using
  5. model_id = 'amazon.titan-text-lite-v1'
  6. # The desired MIME type of the inference body in the response
  7. accept = 'application/json'
  8. # The MIME type of the input data in the request
  9. content_type = 'application/json'
  10. # The maximum number of tokens to use in the generated response
  11. max_tokens_to_sample = 1000
  12. # Sample user demographics
  13. user_demographic_1 = f'The user is a 50 year old adult called Otto.'
  14. user_demographic_3 = f'The user is a young adult called Jane.'
  15. def generate_personalized_prompt(user_demographic, favorite_genre, movie_list, model_id, max_tokens_to_sample = 50):
  16. prompt_template = f'''You are a skilled publicist. Write a high-converting marketing email advertising several movies available in a video-on-demand streaming platform next week,
  17. given the movie and user information below. Your email will leverage the power of storytelling and persuasive language.
  18. You want the email to impress the user, so make it appealing to them based on the information contained in the <user> tags,
  19. and take into account the user's favorite genre in the <genre> tags.
  20. The movies to recommend and their information is contained in the <movie> tag.
  21. All movies in the <movie> tag must be recommended. Give a summary of the movies and why the human should watch them.
  22. Put the email between <email> tags.
  23. Sign it from "Cloud island movies".
  24. <user>
  25. {user_demographic}
  26. </user>
  27. <genre>
  28. {favorite_genre}
  29. </genre>
  30. <movie>
  31. {movie_list}
  32. </movie>
  33. '''
  34. prompt_input = json.dumps({
  35. "inputText":prompt_template,
  36. "textGenerationConfig": {
  37. "maxTokenCount": 4096,
  38. "stopSequences": [],
  39. "temperature": 0.7,
  40. "topP": 0.9
  41. }
  42. })
  43. return prompt_input
  44. # Create prompt input
  45. prompt_input_json = generate_personalized_prompt(user_demographic, user_favorite_genre, movie_list, model_id, max_tokens_to_sample )
  46. prompt_input_json
  47. response = bedrock.invoke_model(
  48. body= prompt_input_json,
  49. modelId=model_id,
  50. accept=accept,
  51. contentType=content_type
  52. )
  53. response_body = json.loads(response.get('body').read())
  54. model_output_string = response_body['results'][0]['outputText']
  55. # model_output_str_clean = re.sub(r'<[^>]*>', '', model_output_string)
  56. print(model_output_string)

 14.最终获得的广告营销邮件内容如下:

以上就是在亚马逊云科技上利用生成式AI搭建面向用户广告营销平台的全部步骤。欢迎大家未来与我一起,未来获取更多国际前沿的生成式AI开发方案。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号