第7章:生成式AI应用

7.1 生成式AI概述

理论讲解

生成式AI是人工智能的一个分支,旨在创建新的内容,如图像、文本、音频、视频等。与判别式AI(用于分类和预测)不同,生成式AI专注于生成新的数据。

生成式AI的核心技术包括:

  • 生成对抗网络(GANs):由生成器和判别器组成,通过对抗训练生成逼真内容
  • 变分自编码器(VAEs):学习数据的潜在分布,用于生成新样本
  • 自回归模型:如GPT系列,通过预测下一个token生成文本
  • 扩散模型:通过逐步去噪生成高质量图像

生成式AI的应用场景非常广泛:

  • 文本生成:文章、故事、代码、诗歌等
  • 图像生成:艺术作品、产品设计、头像等
  • 音频生成:音乐、语音、音效等
  • 视频生成:短视频、动画、特效等

代码示例

// 生成式AI概念的简单演示
function generativeAIBasics() {
  console.log('=== 生成式AI概述 ===');
  
  // 生成式AI类型
  const generativeAITypes = [
    { name: 'GANs', description: '生成对抗网络,用于生成逼真图像' },
    { name: 'VAEs', description: '变分自编码器,用于生成新样本' },
    { name: '自回归模型', description: '如GPT,用于生成文本' },
    { name: '扩散模型', description: '用于生成高质量图像' }
  ];
  
  console.log('生成式AI类型:', generativeAITypes);
  
  // 生成式AI应用场景
  const applications = [
    { domain: '文本生成', examples: ['文章写作', '代码生成', '对话系统'] },
    { domain: '图像生成', examples: ['艺术创作', '产品设计', '头像生成'] },
    { domain: '音频生成', examples: ['音乐创作', '语音合成', '音效生成'] },
    { domain: '视频生成', examples: ['短视频制作', '动画生成', '特效生成'] }
  ];
  
  console.log('生成式AI应用场景:', applications);
  
  // 简单的文本生成示例(基于规则)
  function simpleTextGenerator(prompt) {
    const templates = [
      `${prompt}是一个非常有趣的话题。`,
      `关于${prompt},我有很多想法。`,
      `${prompt}在现代社会中扮演着重要角色。`,
      `研究${prompt}可以帮助我们更好地理解世界。`
    ];
    
    return templates[Math.floor(Math.random() * templates.length)];
  }
  
  const prompt = '生成式AI';
  const generatedText = simpleTextGenerator(prompt);
  console.log(`\n简单文本生成示例:`);
  console.log(`输入:${prompt}`);
  console.log(`输出:${generatedText}`);
}

generativeAIBasics();

实践练习

  1. 描述生成式AI与判别式AI的区别
  2. 列出3种生成式AI技术及其应用场景
  3. 思考:生成式AI可能带来的伦理问题有哪些?

7.2 文本生成技术

理论讲解

文本生成是生成式AI最成熟的应用之一,涉及多种技术和模型:

  1. 基于规则的生成:使用预定义模板和规则生成文本
  2. 统计语言模型:如n-gram模型,基于概率统计生成文本
  3. 神经网络语言模型:使用循环神经网络(RNN)生成文本
  4. Transformer模型:如GPT系列、BERT等,基于注意力机制生成高质量文本

文本生成的评估指标包括:

  • 困惑度(Perplexity):衡量模型预测文本的难度
  • BLEU分数:评估生成文本与参考文本的相似度
  • ROUGE分数:评估文本摘要的质量
  • 人工评估:人类对生成文本质量的主观评价

代码示例

// 基于n-gram的简单文本生成
class NGramTextGenerator {
  constructor(n = 2) {
    this.n = n;
    this.ngrams = new Map();
  }
  
  // 训练模型
  train(text) {
    const tokens = text.split(/\s+/);
    
    for (let i = 0; i <= tokens.length - this.n; i++) {
      const gram = tokens.slice(i, i + this.n - 1).join(' ');
      const nextWord = tokens[i + this.n - 1];
      
      if (!this.ngrams.has(gram)) {
        this.ngrams.set(gram, []);
      }
      
      this.ngrams.get(gram).push(nextWord);
    }
  }
  
  // 生成文本
  generate(startText, length = 10) {
    let current = startText.split(/\s+/).slice(-this.n + 1).join(' ');
    let result = startText;
    
    for (let i = 0; i < length; i++) {
      const nextWords = this.ngrams.get(current);
      if (!nextWords || nextWords.length === 0) {
        break;
      }
      
      const nextWord = nextWords[Math.floor(Math.random() * nextWords.length)];
      result += ' ' + nextWord;
      
      // 更新当前n-gram
      const tokens = result.split(/\s+/);
      current = tokens.slice(-this.n + 1).join(' ');
    }
    
    return result;
  }
}

// 使用示例
const generator = new NGramTextGenerator(2); // 二元语法

const trainingText = `
JavaScript是一种广泛使用的编程语言。
JavaScript主要用于Web开发。
Web开发包括前端和后端。
前端开发涉及HTML、CSS和JavaScript。
后端开发可以使用Node.js。
Node.js是基于JavaScript的运行时环境。
`;

generator.train(trainingText);

const generatedText = generator.generate('JavaScript', 10);
console.log('基于n-gram的文本生成:');
console.log(generatedText);

实践练习

  1. 实现一个简单的基于n-gram的文本生成器
  2. 使用不同的n值(2、3、4)训练模型,比较生成结果
  3. 思考:基于n-gram的文本生成有哪些局限性?

7.3 图像生成技术

理论讲解

图像生成是生成式AI的重要应用领域,主要技术包括:

  1. 生成对抗网络(GANs):由生成器和判别器组成,通过对抗训练生成逼真图像
  2. 变分自编码器(VAEs):学习数据的潜在分布,用于生成新样本
  3. 扩散模型:通过逐步去噪生成高质量图像,如DALL-E、MidJourney等
  4. 风格迁移:将一幅图像的风格迁移到另一幅图像上

图像生成的应用场景包括:

  • 艺术创作:生成绘画、设计等艺术作品
  • 产品设计:生成产品原型、包装设计等
  • 游戏开发:生成游戏场景、角色、道具等
  • 内容创作:生成社交媒体图片、广告素材等

代码示例

// 简单的图像生成演示(基于Canvas)
function generateImage(width = 200, height = 200) {
  // 创建Canvas元素
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  
  // 生成随机背景
  ctx.fillStyle = `hsl(${Math.random() * 360}, 50%, 80%)`;
  ctx.fillRect(0, 0, width, height);
  
  // 生成随机形状
  const shapeCount = Math.floor(Math.random() * 10) + 5;
  for (let i = 0; i < shapeCount; i++) {
    const x = Math.random() * width;
    const y = Math.random() * height;
    const size = Math.random() * 30 + 10;
    const color = `hsl(${Math.random() * 360}, 70%, 60%)`;
    
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2);
    ctx.fill();
  }
  
  // 生成随机线条
  const lineCount = Math.floor(Math.random() * 5) + 2;
  for (let i = 0; i < lineCount; i++) {
    ctx.strokeStyle = `hsl(${Math.random() * 360}, 80%, 40%)`;
    ctx.lineWidth = Math.random() * 3 + 1;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }
  
  return canvas.toDataURL();
}

// 使用示例(在浏览器中运行)
if (typeof document !== 'undefined') {
  const imageUrl = generateImage(300, 300);
  const img = document.createElement('img');
  img.src = imageUrl;
  document.body.appendChild(img);
}

实践练习

  1. 在浏览器中运行上面的代码,生成随机图像
  2. 修改代码,生成不同类型的形状(如矩形、三角形等)
  3. 尝试实现简单的风格迁移效果

7.4 实战:AI写作助手

理论讲解

AI写作助手是文本生成的典型应用,能够帮助用户生成各种类型的文本,如文章、故事、代码、邮件等。在这个实战中,我们将使用OpenAI API实现一个简单的AI写作助手,具备以下功能:

  1. 支持不同类型的文本生成(文章、故事、代码等)
  2. 允许用户调整生成文本的长度和风格
  3. 提供实时生成和显示功能
  4. 支持保存生成的文本

代码示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI写作助手</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            text-align: center;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin: 20px 0;
        }
        .input-section {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
        }
        .form-group {
            margin: 10px 0;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        select, input[type="number"] {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
            width: 200px;
        }
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 100px;
            font-size: 16px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .output-section {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
        }
        #generatedText {
            min-height: 200px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 4px;
            white-space: pre-wrap;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            background-color: #e3f2fd;
            border-radius: 4px;
        }
        .error {
            background-color: #ffebee;
            color: #c62828;
        }
        .success {
            background-color: #e8f5e8;
            color: #2e7d32;
        }
    </style>
</head>
<body>
    <h1>AI写作助手</h1>
    
    <div class="container">
        <div class="input-section">
            <h3>输入参数</h3>
            
            <div class="form-group">
                <label for="apiKey">OpenAI API Key(可选,用于真实生成)</label>
                <input type="password" id="apiKey" placeholder="sk-..." style="width: 300px;">
            </div>
            
            <div class="form-group">
                <label for="textType">文本类型</label>
                <select id="textType">
                    <option value="文章">文章</option>
                    <option value="故事">故事</option>
                    <option value="代码">代码</option>
                    <option value="邮件">邮件</option>
                    <option value="诗歌">诗歌</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="prompt">提示词</label>
                <textarea id="prompt" placeholder="请输入你的写作需求..."></textarea>
            </div>
            
            <div class="form-group">
                <label for="maxLength">最大长度(单词数)</label>
                <input type="number" id="maxLength" value="200" min="50" max="1000">
            </div>
            
            <div class="form-group">
                <label for="temperature">生成温度(0-1,越高越随机)</label>
                <input type="number" id="temperature" value="0.7" min="0" max="1" step="0.1">
            </div>
            
            <button onclick="generateText()">生成文本</button>
            <button onclick="saveText()">保存文本</button>
        </div>
        
        <div class="output-section">
            <h3>生成结果</h3>
            <div id="status" class="status"></div>
            <div id="generatedText"></div>
        </div>
    </div>

    <script>
        // 全局变量
        const apiKeyInput = document.getElementById('apiKey');
        const textTypeSelect = document.getElementById('textType');
        const promptInput = document.getElementById('prompt');
        const maxLengthInput = document.getElementById('maxLength');
        const temperatureInput = document.getElementById('temperature');
        const statusDiv = document.getElementById('status');
        const generatedTextDiv = document.getElementById('generatedText');
        
        // 生成文本函数
        async function generateText() {
            const apiKey = apiKeyInput.value.trim();
            const textType = textTypeSelect.value;
            const prompt = promptInput.value.trim();
            const maxLength = parseInt(maxLengthInput.value);
            const temperature = parseFloat(temperatureInput.value);
            
            if (!prompt) {
                showStatus('请输入提示词', 'error');
                return;
            }
            
            showStatus('正在生成文本...', 'info');
            generatedTextDiv.textContent = '';
            
            try {
                let generatedText;
                
                if (apiKey) {
                    // 使用OpenAI API生成文本
                    generatedText = await generateWithOpenAI(apiKey, prompt, textType, maxLength, temperature);
                } else {
                    // 使用模拟生成(用于演示)
                    generatedText = generateMockText(prompt, textType, maxLength);
                }
                
                generatedTextDiv.textContent = generatedText;
                showStatus('文本生成完成!', 'success');
            } catch (error) {
                showStatus(`生成失败:${error.message}`, 'error');
                console.error('生成错误:', error);
            }
        }
        
        // 使用OpenAI API生成文本
        async function generateWithOpenAI(apiKey, prompt, textType, maxLength, temperature) {
            const response = await fetch('https://api.openai.com/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    model: 'gpt-3.5-turbo',
                    messages: [
                        { role: 'system', content: `你是一个专业的${textType}生成助手。` },
                        { role: 'user', content: prompt }
                    ],
                    max_tokens: maxLength,
                    temperature: temperature
                })
            });
            
            if (!response.ok) {
                throw new Error(`API请求失败:${response.statusText}`);
            }
            
            const data = await response.json();
            return data.choices[0].message.content;
        }
        
        // 模拟文本生成(用于演示)
        function generateMockText(prompt, textType, maxLength) {
            const mockTemplates = {
                '文章': [
                    `${prompt}是一个重要的话题。在现代社会中,${prompt}扮演着越来越重要的角色。`,
                    `关于${prompt},有许多不同的观点和研究。本文将探讨${prompt}的各个方面。`,
                    `${prompt}的发展历程可以追溯到很久以前。随着技术的进步,${prompt}不断演变和完善。`
                ],
                '故事': [
                    `从前,有一个关于${prompt}的故事。在一个遥远的地方,${prompt}改变了一切。`,
                    `当${prompt}出现时,所有人都感到惊讶。没有人预料到${prompt}会带来如此大的影响。`,
                    `在一个平静的小镇上,${prompt}的到来打破了原有的宁静。`
                ],
                '代码': [
                    `// 这是一个关于${prompt}的示例代码\nfunction ${prompt}() {\n    console.log('${prompt}');\n}\n\n${prompt}();`,
                    `/*\n * ${prompt}示例代码\n */\nclass ${prompt.charAt(0).toUpperCase() + prompt.slice(1)} {\n    constructor() {\n        this.name = '${prompt}';\n    }\n}`,
                    `// ${prompt}功能实现\nconst ${prompt} = () => {\n    return 'Hello, ${prompt}!';\n};`
                ],
                '邮件': [
                    `尊敬的收件人:\n\n关于${prompt},我想与您分享一些想法。${prompt}对我们的工作非常重要。\n\n祝好,\n发件人`,
                    `您好!\n\n我写信是想与您讨论${prompt}的相关事宜。${prompt}的进展如何?\n\n期待您的回复。\n此致,\n发件人`
                ],
                '诗歌': [
                    `${prompt}啊,${prompt},\n你是如此美丽。\n在阳光下闪耀,\n在微风中摇曳。`,
                    `当${prompt}来临,\n世界变得不同。\n一切都充满了希望,\n一切都变得美好。`
                ]
            };
            
            const templates = mockTemplates[textType] || mockTemplates['文章'];
            let result = templates[Math.floor(Math.random() * templates.length)];
            
            // 模拟生成更长的文本
            const additionalSentences = [
                `这是关于${prompt}的补充内容。`,
                `${prompt}的重要性不容忽视。`,
                `我们需要进一步研究${prompt}。`,
                `${prompt}的未来充满了可能性。`,
                `让我们一起探索${prompt}的奥秘。`
            ];
            
            const numSentences = Math.floor(maxLength / 20); // 粗略估计
            for (let i = 0; i < numSentences; i++) {
                result += ' ' + additionalSentences[Math.floor(Math.random() * additionalSentences.length)];
            }
            
            return result;
        }
        
        // 保存文本
        function saveText() {
            const text = generatedTextDiv.textContent;
            if (!text) {
                showStatus('没有可保存的文本', 'error');
                return;
            }
            
            const blob = new Blob([text], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `ai-generated-${Date.now()}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showStatus('文本已保存!', 'success');
        }
        
        // 显示状态
        function showStatus(message, type = 'info') {
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            showStatus('请输入提示词并点击生成按钮');
        });
    </script>
</body>
</html>

实践练习

  1. 运行上面的代码,测试AI写作助手功能
  2. 尝试不同类型的文本生成,观察结果
  3. 注册OpenAI账号,获取API Key,测试真实的文本生成
  4. 改进代码,添加更多文本类型和生成选项
  5. 思考:如何提高AI生成文本的质量和相关性?

章节总结

核心知识点回顾

  1. 生成式AI的基本概念和核心技术
  2. 文本生成技术,包括n-gram模型和Transformer模型
  3. 图像生成技术,包括GANs、VAEs和扩散模型
  4. 使用OpenAI API实现AI写作助手

学习收获

  • 理解了生成式AI的基本原理和应用
  • 掌握了基于n-gram的简单文本生成方法
  • 了解了图像生成的主要技术和应用场景
  • 实现了一个功能完整的AI写作助手

下一步学习

在下一章中,我们将学习模型部署与优化,包括模型压缩、部署策略和性能监控等内容,为AI应用的生产环境部署做好准备。


课程分类:前端开发、AI技术开发

学习建议

  • 关注生成式AI领域的最新发展,如GPT-4、DALL-E 3等
  • 学习使用不同的生成式AI API,如OpenAI、Anthropic等
  • 实践微调预训练模型,适应特定任务需求
  • 了解生成式AI的伦理问题和最佳实践

资源链接

« 上一篇 自然语言处理 下一篇 » 模型部署与优化