你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
快速入门:个性化体验创建服务客户端库
在本快速入门中使用个性化体验创建服务显示个性化内容。
个性化体验创建服务客户端库入门。 请按照以下步骤安装程序包并试用基本任务的示例代码。
- 排名 API - 根据你提供的有关内容和上下文的实时信息,从操作中选择最佳项。
- 奖励 API - 根据业务需要确定奖励分数,然后使用此 API 将其发送给个性化体验创建服务。 该分数可以是单个值(例如,1 表示“好”,0 表示“差”),也可以是你根据业务需求创建的算法。
先决条件
- Azure 订阅 - 免费创建订阅
- .NET Core 的当前版本。
- 拥有 Azure 订阅后,在 Azure 门户中创建个性化体验创建服务资源,获取密钥和终结点。 部署后,单击“转到资源”。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到个性化体验创建服务 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
F0
) 试用该服务,然后再升级到付费层进行生产。
设置
更改模型更新频率
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“模型更新频率”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
首次实例化个性化体验创建服务循环时,由于没有奖励 API 调用可供训练,因此没有模型。 排名调用将为每个项返回相等的概率。 你的应用程序仍应始终使用 RewardActionId 的输出对内容进行排名。
更改奖励等待时间
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“奖励等待时间”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
新建 C# 应用程序
在首选编辑器或 IDE 中创建新的 .NET Core 应用程序。
在控制台窗口(例如 CMD、PowerShell 或 Bash)中,使用 dotnet new
命令创建名为 personalizer-quickstart
的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.cs
。
dotnet new console -n personalizer-quickstart
将目录更改为新创建的应用文件夹。 可使用以下代码生成应用程序:
dotnet build
生成输出不应包含警告或错误。
...
Build succeeded.
0 Warning(s)
0 Error(s)
...
安装客户端库
在应用程序目录中,使用以下命令安装适用于 .NET 的个性化体验创建服务客户端库:
dotnet add package Microsoft.Azure.CognitiveServices.Personalizer --version 1.0.0
提示
如果你使用的是 Visual Studio IDE,客户端库可用作可下载的 NuGet 包。
在偏好的编辑器或 IDE 中打开项目目录中的 Program.cs
文件。 添加以下 using 指令:
using Microsoft.Azure.CognitiveServices.Personalizer;
using Microsoft.Azure.CognitiveServices.Personalizer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
对象模型
个性化体验创建服务客户端是 PersonalizerClient 对象,使用包含密钥的 Microsoft.Rest.ServiceClientCredentials 向 Azure 进行身份验证。
若要请求内容的单一最佳项,请创建一个 RankRequest,然后将其传递给 client.Rank 方法。 Rank 方法返回 RankResponse。
若要向个性化体验创建服务发送奖励评分,请创建一个 RewardRequest,然后将其传递给 client.Reward 方法。
在本快速入门中,可以很容易地确定奖励评分。 在生产系统中,确定哪些因素会影响奖励评分以及影响程度可能是一个复杂的过程,你的判断可能会随时改变。 此设计决策应是个性化体验创建服务体系结构中的主要决策之一。
代码示例
这些代码片段演示如何使用适用于 .NET 的个性化体验创建服务客户端库执行以下任务:
验证客户端
在本部分中,你将执行以下两项操作:
- 指定密钥和终结点
- 创建个性化体验创建服务客户端
首先,将以下行添加到 Program 类。 请确保从个性化体验创建服务资源中添加密钥和终结点。
重要
转到 Azure 门户。 如果在“先决条件”部分中创建的个性化体验创建服务资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 例如,Azure 密钥保管库。
private static readonly string ApiKey = "REPLACE-WITH-YOUR-PERSONALIZER-KEY";
private static readonly string ServiceEndpoint = "https://REPLACE-WITH-YOUR-PERSONALIZER-RESOURCE-NAME.cognitiveservices.azure.com";
接下来,将方法添加到程序,以创建新的个性化体验创建服务客户端。
static PersonalizerClient InitializePersonalizerClient(string url)
{
PersonalizerClient client = new PersonalizerClient(
new ApiKeyServiceClientCredentials(ApiKey)) { Endpoint = url };
return client;
}
获取食品项作为可排名操作
操作表示你希望个性化体验创建服务从中选择最佳内容项的内容选择。 将以下方法添加到 Program 类,以表示操作及其特征的集合。
static IList<RankableAction> GetActions()
{
IList<RankableAction> actions = new List<RankableAction>
{
new RankableAction
{
Id = "pasta",
Features =
new List<object>() { new { taste = "salty", spiceLevel = "medium" }, new { nutritionLevel = 5, cuisine = "italian" } }
},
new RankableAction
{
Id = "ice cream",
Features =
new List<object>() { new { taste = "sweet", spiceLevel = "none" }, new { nutritionalLevel = 2 } }
},
new RankableAction
{
Id = "juice",
Features =
new List<object>() { new { taste = "sweet", spiceLevel = "none" }, new { nutritionLevel = 5 }, new { drink = true } }
},
new RankableAction
{
Id = "salad",
Features =
new List<object>() { new { taste = "salty", spiceLevel = "low" }, new { nutritionLevel = 8 } }
}
};
return actions;
}
获取上下文的用户首选项
将以下方法添加到 Program 类,以从命令行获取用户的日期时间输入及其当前食品偏好。 它们将用作上下文特征。
static string GetUsersTimeOfDay()
{
string[] timeOfDayFeatures = new string[] { "morning", "afternoon", "evening", "night" };
Console.WriteLine("\nWhat time of day is it (enter number)? 1. morning 2. afternoon 3. evening 4. night");
if (!int.TryParse(GetKey(), out int timeIndex) || timeIndex < 1 || timeIndex > timeOfDayFeatures.Length)
{
Console.WriteLine("\nEntered value is invalid. Setting feature value to " + timeOfDayFeatures[0] + ".");
timeIndex = 1;
}
return timeOfDayFeatures[timeIndex - 1];
}
static string GetUsersTastePreference()
{
string[] tasteFeatures = new string[] { "salty", "sweet" };
Console.WriteLine("\nWhat type of food would you prefer (enter number)? 1. salty 2. sweet");
if (!int.TryParse(GetKey(), out int tasteIndex) || tasteIndex < 1 || tasteIndex > tasteFeatures.Length)
{
Console.WriteLine("\nEntered value is invalid. Setting feature value to " + tasteFeatures[0] + ".");
tasteIndex = 1;
}
return tasteFeatures[tasteIndex - 1];
}
这两个方法都使用 GetKey
方法从命令行读取用户的选择。
private static string GetKey()
{
return Console.ReadKey().Key.ToString().Last().ToString().ToUpper();
}
创建学习循环
个性化体验创建服务学习循环是一个排名和奖励调用周期。 在本快速入门中,用于个性化内容的每个排名调用都后接一个奖励调用,该奖励调用让个性化体验创建服务知道该服务的表现如何。
以下代码循环调用以下循环:在命令行询问用户的首选项,将该信息发送给个性化体验创建服务以选择最佳操作,向客户显示所选项以让他们从列表中进行选择,然后向个性化体验创建服务发送奖励评分,指出服务在做选择时的表现如何。
static void Main(string[] args)
{
int iteration = 1;
bool runLoop = true;
IList<RankableAction> actions = GetActions();
PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);
do
{
Console.WriteLine("\nIteration: " + iteration++);
string timeOfDayFeature = GetUsersTimeOfDay();
string tasteFeature = GetUsersTastePreference();
IList<object> currentContext = new List<object>() {
new { time = timeOfDayFeature },
new { taste = tasteFeature }
};
IList<string> excludeActions = new List<string> { "juice" };
string eventId = Guid.NewGuid().ToString();
var request = new RankRequest(actions, currentContext, excludeActions, eventId);
RankResponse response = client.Rank(request);
Console.WriteLine("\nPersonalizer service thinks you would like to have: " + response.RewardActionId + ". Is this correct? (y/n)");
float reward = 0.0f;
string answer = GetKey();
if (answer == "Y")
{
reward = 1;
Console.WriteLine("\nGreat! Enjoy your food.");
}
else if (answer == "N")
{
reward = 0;
Console.WriteLine("\nYou didn't like the recommended food choice.");
}
else
{
Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended food choice.");
}
Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
foreach (var rankedResponse in response.Ranking)
{
Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
}
client.Reward(response.EventId, new RewardRequest(reward));
Console.WriteLine("\nPress q to break, any other key to continue:");
runLoop = !(GetKey() == "Q");
} while (runLoop);
}
在运行代码文件之前,添加以下方法以获取内容选项:
GetActions
GetUsersTimeOfDay
GetUsersTastePreference
GetKey
请求最佳操作
为了完成排名请求,程序将要求用户指定偏好,以创建内容选项的 currentContext
。 该过程可以创建要从操作中排除的内容,显示为 excludeActions
。 排名请求需要 actions 及其特征、currentContext 特征、excludeActions 以及唯一的事件 ID 才能接收响应。
本快速入门使用简单的日期时间和用户食品偏好上下文特征。 在生产系统中,确定和评估操作与特征可能是一件非常重要的事情。
string timeOfDayFeature = GetUsersTimeOfDay();
string tasteFeature = GetUsersTastePreference();
IList<object> currentContext = new List<object>() {
new { time = timeOfDayFeature },
new { taste = tasteFeature }
};
IList<string> excludeActions = new List<string> { "juice" };
string eventId = Guid.NewGuid().ToString();
var request = new RankRequest(actions, currentContext, excludeActions, eventId);
RankResponse response = client.Rank(request);
发送奖励
为了获取奖励评分以在奖励请求中发送,程序将从命令行获取用户的选择,为该选择分配一个数值,然后将唯一事件 ID 和奖励评分(作为数值)发送到奖励 API。
本快速入门分配一个简单的数字(0 或 1)作为奖励评分。 在生产系统中,确定何时向奖励调用发送哪种内容可能不是一个简单的过程,这取决于具体的需求。
float reward = 0.0f;
string answer = GetKey();
if (answer == "Y")
{
reward = 1;
Console.WriteLine("\nGreat! Enjoy your food.");
}
else if (answer == "N")
{
reward = 0;
Console.WriteLine("\nYou didn't like the recommended food choice.");
}
else
{
Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended food choice.");
}
Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
foreach (var rankedResponse in response.Ranking)
{
Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
}
// Send the reward for the action based on user response.
client.Reward(response.EventId, new RewardRequest(reward));
运行程序
从应用程序目录,使用 dotnet run
命令运行应用程序。
dotnet run
其中还有本快速入门的源代码。
先决条件
- Azure 订阅 - 免费创建订阅
- 安装 Node.js 和 NPM(通过 Node.js v14.16.0 和 NPM 6.14.11 验证)。
- 拥有 Azure 订阅后,在 Azure 门户中创建个性化体验创建服务资源,获取密钥和终结点。 部署后,单击“转到资源”。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到个性化体验创建服务 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
F0
) 试用该服务,然后再升级到付费层进行生产。
设置
更改模型更新频率
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“模型更新频率”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
首次实例化个性化体验创建服务循环时,由于没有奖励 API 调用可供训练,因此没有模型。 排名调用将为每个项返回相等的概率。 你的应用程序仍应始终使用 RewardActionId 的输出对内容进行排名。
更改奖励等待时间
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“奖励等待时间”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
创建新的 Node.js 应用程序
在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。
mkdir myapp && cd myapp
运行 npm init -y
命令以创建 package.json
文件。
npm init -y
在首选编辑器或名为 sample.js
的 IDE 中创建新的 Node.js 应用程序,并创建资源的终结点和订阅密钥的变量。
重要
转到 Azure 门户。 如果在“先决条件”部分中创建的个性化体验创建服务资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 例如,Azure 密钥保管库。
const uuidv1 = require('uuid/v1');
const Personalizer = require('@azure/cognitiveservices-personalizer');
const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
const readline = require('readline-sync');
// The key specific to your personalization service instance; e.g. "0123456789abcdef0123456789ABCDEF"
const serviceKey = "<REPLACE-WITH-YOUR-PERSONALIZER-KEY>";
// The endpoint specific to your personalization service instance;
// e.g. https://<your-resource-name>.cognitiveservices.azure.com
const baseUri = "https://<REPLACE-WITH-YOUR-PERSONALIZER-ENDPOINT>.cognitiveservices.azure.com";
为个性化体验创建服务安装 Node.js 库
使用以下命令安装适用于 Node.js 的个性化体验创建服务客户端库:
npm install @azure/cognitiveservices-personalizer --save
安装此快速入门的其余 NPM 包:
npm install @azure/ms-rest-azure-js @azure/ms-rest-js readline-sync uuid --save
对象模型
个性化体验创建服务客户端是 PersonalizerClient 对象,使用包含密钥的 Microsoft.Rest.ServiceClientCredentials 向 Azure 进行身份验证。
若要请求内容的单一最佳项,请创建一个 RankRequest,然后将其传递给 client.Rank 方法。 Rank 方法返回 RankResponse。
若要向个性化体验创建服务发送奖励,请创建一个 RewardRequest,然后将其传递给 Events 类的 Reward 方法。
在本快速入门中,可以很容易地确定奖励。 在生产系统中,确定哪些因素会影响奖励评分以及影响程度可能是一个复杂的过程,你的判断可能会随时改变。 这应是个性化体验创建服务体系结构中的主要设计决策之一。
代码示例
这些代码片段演示如何使用适用于 Node.js 的个性化体验创建服务客户端库执行以下操作:
验证客户端
使用之前创建的 serviceKey
和 baseUri
实例化 PersonalizerClient
。
const credentials = new CognitiveServicesCredentials(serviceKey);
// Initialize Personalization client.
const personalizerClient = new Personalizer.PersonalizerClient(credentials, baseUri);
获取以操作形式表示的内容选项
操作表示你希望个性化体验创建服务从中选择最佳内容项的内容选择。 将以下方法添加到 Program 类,以表示操作及其特征的集合。
function getContextFeaturesList() {
const timeOfDayFeatures = ['morning', 'afternoon', 'evening', 'night'];
const tasteFeatures = ['salty', 'sweet'];
let answer = readline.question("\nWhat time of day is it (enter number)? 1. morning 2. afternoon 3. evening 4. night\n");
let selection = parseInt(answer);
const timeOfDay = selection >= 1 && selection <= 4 ? timeOfDayFeatures[selection - 1] : timeOfDayFeatures[0];
answer = readline.question("\nWhat type of food would you prefer (enter number)? 1. salty 2. sweet\n");
selection = parseInt(answer);
const taste = selection >= 1 && selection <= 2 ? tasteFeatures[selection - 1] : tasteFeatures[0];
console.log("Selected features:\n");
console.log("Time of day: " + timeOfDay + "\n");
console.log("Taste: " + taste + "\n");
return [
{
"time": timeOfDay
},
{
"taste": taste
}
];
}
function getActionsList() {
return [
{
"id": "pasta",
"features": [
{
"taste": "salty",
"spiceLevel": "medium"
},
{
"nutritionLevel": 5,
"cuisine": "italian"
}
]
},
{
"id": "ice cream",
"features": [
{
"taste": "sweet",
"spiceLevel": "none"
},
{
"nutritionalLevel": 2
}
]
},
{
"id": "juice",
"features": [
{
"taste": "sweet",
"spiceLevel": "none"
},
{
"nutritionLevel": 5
},
{
"drink": true
}
]
},
{
"id": "salad",
"features": [
{
"taste": "salty",
"spiceLevel": "low"
},
{
"nutritionLevel": 8
}
]
}
];
}
创建学习循环
个性化体验创建服务学习循环是一个排名和奖励调用周期。 在本快速入门中,用于个性化内容的每个排名调用都后接一个奖励调用,该奖励调用让个性化体验创建服务知道该服务的表现如何。
以下代码循环调用以下循环:在命令行询问用户的首选项,将该信息发送给个性化体验创建服务以选择最佳操作,向客户显示所选项以让他们从列表中进行选择,然后向个性化体验创建服务发送奖励,指出服务在做选择时的表现如何。
let runLoop = true;
do {
let rankRequest = {}
// Generate an ID to associate with the request.
rankRequest.eventId = uuidv1();
// Get context information from the user.
rankRequest.contextFeatures = getContextFeaturesList();
// Get the actions list to choose from personalization with their features.
rankRequest.actions = getActionsList();
// Exclude an action for personalization ranking. This action will be held at its current position.
rankRequest.excludedActions = getExcludedActionsList();
rankRequest.deferActivation = false;
// Rank the actions
const rankResponse = await personalizerClient.rank(rankRequest);
console.log("\nPersonalization service thinks you would like to have:\n")
console.log(rankResponse.rewardActionId);
// Display top choice to user, user agrees or disagrees with top choice
const reward = getReward();
console.log("\nPersonalization service ranked the actions with the probabilities as below:\n");
for (let i = 0; i < rankResponse.ranking.length; i++) {
console.log(JSON.stringify(rankResponse.ranking[i]) + "\n");
}
// Send the reward for the action based on user response.
const rewardRequest = {
value: reward
}
await personalizerClient.events.reward(rankRequest.eventId, rewardRequest);
runLoop = continueLoop();
} while (runLoop);
在接下来的部分中,让我们仔细看看排名和奖励调用。
在运行代码文件之前,添加以下方法以获取内容选项:
- getActionsList
- getContextFeaturesList
请求最佳操作
为了完成排名请求,程序会询问用户的首选项以创建内容选项。 该过程可以创建要从操作中排除的内容,显示为 excludeActions
。 排名请求需要 actions 及其特征、currentContext 特征、excludeActions 以及唯一的排名事件 ID 才能接收排名的响应。
本快速入门使用简单的日期时间和用户食品偏好上下文特征。 在生产系统中,确定和评估操作与特征可能是一件非常重要的事情。
let rankRequest = {}
// Generate an ID to associate with the request.
rankRequest.eventId = uuidv1();
// Get context information from the user.
rankRequest.contextFeatures = getContextFeaturesList();
// Get the actions list to choose from personalization with their features.
rankRequest.actions = getActionsList();
// Exclude an action for personalization ranking. This action will be held at its current position.
rankRequest.excludedActions = getExcludedActionsList();
rankRequest.deferActivation = false;
// Rank the actions
const rankResponse = await personalizerClient.rank(rankRequest);
发送奖励
为了获取奖励评分以在奖励请求中发送,程序将从命令行获取用户的选择,为该选择分配一个数值,然后将唯一事件 ID 和奖励评分(作为数值)发送到奖励 API。
本快速入门分配一个简单的数字(0 或 1)作为奖励评分。 在生产系统中,确定何时向奖励调用发送哪种内容可能不是一个简单的过程,这取决于具体的需求。
const rewardRequest = {
value: reward
}
await personalizerClient.events.reward(rankRequest.eventId, rewardRequest);
运行程序
从应用程序目录使用 Node.js 运行应用程序。
node sample.js
先决条件
- Azure 订阅 - 免费创建订阅
- Python 3.x
- 拥有 Azure 订阅后,在 Azure 门户中创建个性化体验创建服务资源,获取密钥和终结点。 部署后,单击“转到资源”。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到个性化体验创建服务 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
F0
) 试用该服务,然后再升级到付费层进行生产。
设置
更改模型更新频率
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“模型更新频率”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
首次实例化个性化体验创建服务循环时,由于没有奖励 API 调用可供训练,因此没有模型。 排名调用将为每个项返回相等的概率。 你的应用程序仍应始终使用 RewardActionId 的输出对内容进行排名。
更改奖励等待时间
在 Azure 门户的“配置”页上的个性化体验创建服务资源中,将“奖励等待时间”更改为 30 秒。 此短暂持续时间可快速训练服务,使你可以看到顶部操作如何针对每次迭代而变化。
安装客户端库
在安装 Python 后,可以通过以下命令安装客户端库:
pip install azure-cognitiveservices-personalizer
创建新的 Python 应用程序
创建一个新的 Python 文件,为资源的终结点和订阅密钥创建变量。
重要
转到 Azure 门户。 如果在“先决条件”部分中创建的个性化体验创建服务资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 例如,Azure 密钥保管库。
from azure.cognitiveservices.personalizer import PersonalizerClient
from azure.cognitiveservices.personalizer.models import RankableAction, RewardRequest, RankRequest
from msrest.authentication import CognitiveServicesCredentials
import datetime, json, os, time, uuid
key = "<paste-your-personalizer-key-here>"
endpoint = "<paste-your-personalizer-endpoint-here>"
对象模型
个性化体验创建服务客户端是 PersonalizerClient 对象,使用包含密钥的 Microsoft.Rest.ServiceClientCredentials 向 Azure 进行身份验证。
若要请求内容的单一最佳项,请创建一个 RankRequest,然后将其传递给 client.Rank 方法。 Rank 方法返回 RankResponse。
若要将奖励评分发送到个性化体验创建服务,请设置要发送到 EventOperations 类的 Reward 方法的事件 ID 和奖励评分(值)。
在本快速入门中,可以很容易地确定奖励。 在生产系统中,确定哪些因素会影响奖励评分以及影响程度可能是一个复杂的过程,你的判断可能会随时改变。 这应是个性化体验创建服务体系结构中的主要设计决策之一。
代码示例
这些代码片段演示如何使用适用于 Python 的个性化体验创建服务客户端库执行以下操作:
验证客户端
使用之前创建的 key
和 endpoint
实例化 PersonalizerClient
。
# Instantiate a Personalizer client
client = PersonalizerClient(endpoint, CognitiveServicesCredentials(key))
获取以操作形式表示的内容选项
操作表示你希望个性化体验创建服务从中选择最佳内容项的内容选择。 将以下方法添加到 Program 类,以表示操作及其特征的集合。
def get_actions():
action1 = RankableAction(id='pasta', features=[{"taste":"salty", "spice_level":"medium"},{"nutrition_level":5,"cuisine":"italian"}])
action2 = RankableAction(id='ice cream', features=[{"taste":"sweet", "spice_level":"none"}, { "nutritional_level": 2 }])
action3 = RankableAction(id='juice', features=[{"taste":"sweet", 'spice_level':'none'}, {'nutritional_level': 5}, {'drink':True}])
action4 = RankableAction(id='salad', features=[{'taste':'salty', 'spice_level':'none'},{'nutritional_level': 2}])
return [action1, action2, action3, action4]
def get_user_timeofday():
res={}
time_features = ["morning", "afternoon", "evening", "night"]
time = input("What time of day is it (enter number)? 1. morning 2. afternoon 3. evening 4. night\n")
try:
ptime = int(time)
if(ptime<=0 or ptime>len(time_features)):
raise IndexError
res['time_of_day'] = time_features[ptime-1]
except (ValueError, IndexError):
print("Entered value is invalid. Setting feature value to", time_features[0] + ".")
res['time_of_day'] = time_features[0]
return res
def get_user_preference():
res = {}
taste_features = ['salty','sweet']
pref = input("What type of food would you prefer? Enter number 1.salty 2.sweet\n")
try:
ppref = int(pref)
if(ppref<=0 or ppref>len(taste_features)):
raise IndexError
res['taste_preference'] = taste_features[ppref-1]
except (ValueError, IndexError):
print("Entered value is invalid. Setting feature value to", taste_features[0]+ ".")
res['taste_preference'] = taste_features[0]
return res
创建学习循环
个性化体验创建服务学习循环是一个排名和奖励调用周期。 在本快速入门中,用于个性化内容的每个排名调用都后接一个奖励调用,该奖励调用让个性化体验创建服务知道该服务的表现如何。
以下代码循环调用以下循环:在命令行询问用户的首选项,将该信息发送给个性化体验创建服务以选择最佳操作,向客户显示所选项以让他们从列表中进行选择,然后向个性化体验创建服务发送奖励,指出服务在做选择时的表现如何。
keep_going = True
while keep_going:
eventid = str(uuid.uuid4())
context = [get_user_preference(), get_user_timeofday()]
actions = get_actions()
rank_request = RankRequest( actions=actions, context_features=context, excluded_actions=['juice'], event_id=eventid)
response = client.rank(rank_request=rank_request)
print("Personalizer service ranked the actions with the probabilities listed below:")
rankedList = response.ranking
for ranked in rankedList:
print(ranked.id, ':',ranked.probability)
print("Personalizer thinks you would like to have", response.reward_action_id+".")
answer = input("Is this correct?(y/n)\n")[0]
reward_val = "0.0"
if(answer.lower()=='y'):
reward_val = "1.0"
elif(answer.lower()=='n'):
reward_val = "0.0"
else:
print("Entered choice is invalid. Service assumes that you didn't like the recommended food choice.")
client.events.reward(event_id=eventid, value=reward_val)
br = input("Press Q to exit, any other key to continue: ")
if(br.lower()=='q'):
keep_going = False
在运行代码文件之前,添加以下方法以获取内容选项:
get_user_preference
get_user_timeofday
get_actions
请求最佳操作
为了完成排名请求,程序将要求用户指定偏好,以创建内容选项的 currentContent
。 该过程可以创建要从操作中排除的内容,显示为 excludeActions
。 排名请求需要 actions 及其特征、currentContext 特征、excludeActions 以及唯一的事件 ID 才能接收响应。
本快速入门使用简单的日期时间和用户食品偏好上下文特征。 在生产系统中,确定和评估操作与特征可能是一件非常重要的事情。
rank_request = RankRequest( actions=actions, context_features=context, excluded_actions=['juice'], event_id=eventid)
response = client.rank(rank_request=rank_request)
发送奖励
为了获取奖励评分以在奖励请求中发送,程序将从命令行获取用户的选择,为该选择分配一个数值,然后将唯一事件 ID 和奖励评分(作为数值)发送到奖励 API。
本快速入门分配一个简单的数字(0 或 1)作为奖励评分。 在生产系统中,确定何时向奖励调用发送哪种内容可能不是一个简单的过程,这取决于具体的需求。
reward_val = "0.0"
if(answer.lower()=='y'):
reward_val = "1.0"
elif(answer.lower()=='n'):
reward_val = "0.0"
else:
print("Entered choice is invalid. Service assumes that you didn't like the recommended food choice.")
client.events.reward(event_id=eventid, value=reward_val)
运行程序
从应用程序目录使用 python 运行应用程序。
python sample.py
清理资源
如果想要清理并删除认知服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。