目录
设置TensorFlow.js代码
小莎士比亚数据集
通用句子编码器
莎士比亚独白在行动
终点线
总结
- 下载项目代码-9.9 MB
TensorFlow + JavaScript。现在,最流行、最先进的AI框架支持地球上使用最广泛的编程语言。因此,让我们在Web浏览器中通过深度学习使文本和NLP(自然语言处理)聊天机器人神奇地发生,使用TensorFlow.js通过WebGL加速GPU!
这是莎士比亚。在本文(系列的最后一篇)中,我们将使用AI生成一些莎士比亚独白。此处为上一篇文章链接。
设置TensorFlow.js代码该项目在单个网页中运行。我们将包括TensorFlow.js和通用句子编码器(USE),这是一种基于转换器的预训练语言处理模型。我们将bot输出打印到页面上。两个附加的实用函数,dotProduct并且zipWith,从USE自述例子,将帮助我们确定句子相似度。
Shakespearean Monologue Bot: Chatbots in the Browser with TensorFlow.js
Shakespearean Monologue Bot
function setText( text ) {
document.getElementById( "status" ).innerText = text;
}
// Calculate the dot product of two vector arrays.
const dotProduct = (xs, ys) => {
const sum = xs => xs ? xs.reduce((a, b) => a + b, 0) : undefined;
return xs.length === ys.length ?
sum(zipWith((a, b) => a * b, xs, ys))
: undefined;
}
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith =
(f, xs, ys) => {
const ny = ys.length;
return (xs.length f(x, ys[i]));
}
(async () => {
// Your Code Goes Here
})();
小莎士比亚数据集
对于这个项目,我们的机器人将使用TinyShakespeare数据集的引用生成自己的莎士比亚脚本。它包含来自莎士比亚戏剧的4万行文字。我们将使用它来创建短语及其“下一个短语”的集合。
让我们遍历每一行以填充消息数组和匹配的响应数组。该代码应如下所示:
let shakespeare_lines = await fetch( "web/tinyshakespeare.txt" ).then( r => r.text() );
let lines = shakespeare_lines.split( "\n" ).filter( x => !!x ); // Split & remove empty lines
let messages = [];
let responses = [];
for( let i = 0; i < lines.length - 1; i++ ) {
messages.push( lines[ i ] );
responses.push( lines[ i + 1 ] );
}
通用句子编码器
通用编码器句(USE)是“[预先训练]模型编码文本转换成512维的嵌入”。有关USE及其体系结构的完整说明,请参阅本系列前面的“改进的情绪检测”文章。
USE易于使用。让我们在定义网络模型并使用其QnA双编码器之前将其加载到代码中,这将为我们提供所有查询和所有答案的全语句嵌入,其性能应比单词嵌入更好。我们可以使用它来确定最相似的当前消息和响应。
// Load the universal sentence encoder
setText( "Loading USE..." );
let encoder = await use.load();
setText( "Loaded!" );
const model = await use.loadQnA();
莎士比亚独白在行动
因为句子嵌入已经将相似性编码到其向量中,所以我们不需要训练单独的模型。从每3秒一次的硬编码行"ROMEO:"开始,我们将随机选择200行的子集,并让USE进行艰苦的工作。它将使用QnA编码器找出那些行中的哪一条与最后打印的行最相似,然后查找响应。
// Add to the monologue every 3s
setInterval( async () => {
// Run the calculation things
const numSamples = 200;
let randomOffset = Math.floor( Math.random() * messages.length );
const input = {
queries: [ text ],
responses: messages.slice( randomOffset, numSamples )
};
let embeddings = await model.embed( input );
tf.tidy( () => {
const embed_query = embeddings[ "queryEmbedding" ].arraySync();
const embed_responses = embeddings[ "responseEmbedding" ].arraySync();
let scores = [];
embed_responses.forEach( response => {
scores.push( dotProduct( embed_query[ 0 ], response ) );
});
let id = scores.indexOf( Math.max( ...scores ) );
text = responses[ randomOffset + id ];
document.getElementById( "bot-text" ).innerText += text + "\n";
});
embeddings.queryEmbedding.dispose();
embeddings.responseEmbedding.dispose();
}, 3000 );
现在,当您打开页面时,它将开始每3秒写一行莎士比亚作品。
这是将所有内容组合在一起的代码:
Shakespearean Monologue Bot: Chatbots in the Browser with TensorFlow.js
Shakespearean Monologue Bot
function setText( text ) {
document.getElementById( "status" ).innerText = text;
}
// Calculate the dot product of two vector arrays.
const dotProduct = (xs, ys) => {
const sum = xs => xs ? xs.reduce((a, b) => a + b, 0) : undefined;
return xs.length === ys.length ?
sum(zipWith((a, b) => a * b, xs, ys))
: undefined;
}
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith =
(f, xs, ys) => {
const ny = ys.length;
return (xs.length f(x, ys[i]));
}
(async () => {
let shakespeare_lines = await fetch( "web/tinyshakespeare.txt" ).then( r => r.text() );
let lines = shakespeare_lines.split( "\n" ).filter( x => !!x ); // Split & remove empty lines
let messages = [];
let responses = [];
for( let i = 0; i < lines.length - 1; i++ ) {
messages.push( lines[ i ] );
responses.push( lines[ i + 1 ] );
}
// Load the universal sentence encoder
setText( "Loading USE..." );
let encoder = await use.load();
setText( "Loaded!" );
const model = await use.loadQnA();
let text = "ROMEO:";
// Add to the monologue every 3s
setInterval( async () => {
// Run the calculation things
const numSamples = 200;
let randomOffset = Math.floor( Math.random() * messages.length );
const input = {
queries: [ text ],
responses: messages.slice( randomOffset, numSamples )
};
let embeddings = await model.embed( input );
tf.tidy( () => {
const embed_query = embeddings[ "queryEmbedding" ].arraySync();
const embed_responses = embeddings[ "responseEmbedding" ].arraySync();
let scores = [];
embed_responses.forEach( response => {
scores.push( dotProduct( embed_query[ 0 ], response ) );
});
let id = scores.indexOf( Math.max( ...scores ) );
text = responses[ randomOffset + id ];
document.getElementById( "bot-text" ).innerText += text + "\n";
});
embeddings.queryEmbedding.dispose();
embeddings.responseEmbedding.dispose();
}, 3000 );
})();
总结
本文以及本系列中的其他文章展示了如何在浏览器中直接使用TensorFlow.js和文本数据,以及诸如USE之类的转换器架构模型的功能,以完成自然语言处理任务和构建聊天机器人。
我希望这些例子能激发您在AI和深度学习上做更多的事情。
https://www.codeproject.com/Articles/5282696/AI-Chatbots-With-TensorFlow-js-Generating-Shakespe