Ai创想实验室是专门为中小学AI教育开发的教学平台,包含了值计算、图像分类、音频分类、文本分类、数值回归、图像回归、图像分类+回归、平衡杆、手写数字生成、文本生成等中小学人工智能学习类项目。无需编程基础、无需添加硬件、无需购买算力、无隐私担忧、无需师资培训即可进行教学实践。

        本文介绍文本生成模型的构建、数据清洗、训练、预测。使用序列补全模式,该模式更易于训练,非序列补全模式将在后续文章介绍:

一、搭建模型

        对于名字生成任务,词汇表无需很大,一般几百到上千就可以了,首先使用Embedding层然后使用LSTM层,注意它们的参数对应关系:

        实际上到这一步就可以进行输出了,其输出维度大小即词汇表大小:

        但为了取得更好的训练效果,我们添加Dropout层强迫模型学习和全连接层增加一些非线性:

        最终的模型如下(JSON):

{
  "success": true,
  "modelConfig": {
    "className": "Sequential",
    "config": {
      "name": "nnblockly_model",
      "layers": [
        {
          "className": "InputLayer",
          "config": {
            "name": "input_layer_1",
            "inputShape": [
              10
            ],
            "batchInputShape": [
              null,
              10
            ],
            "dtype": "float32",
            "sparse": false
          }
        },
        {
          "className": "Embedding",
          "config": {
            "name": "embedding_1",
            "trainable": true,
            "inputDim": 600,
            "outputDim": 64,
            "inputLength": 10,
            "maskZero": true,
            "embeddingsInitializer": {
              "className": "RandomUniform",
              "config": {
                "minval": -0.05,
                "maxval": 0.05,
                "seed": null
              }
            },
            "embeddingsRegularizer": null
          },
          "inboundNodes": [
            [
              [
                "input_layer_1",
                0,
                0,
                []
              ]
            ]
          ]
        },
        {
          "className": "LSTM",
          "config": {
            "name": "lstm_layer_1",
            "trainable": true,
            "units": 64,
            "activation": "tanh",
            "recurrentActivation": "sigmoid",
            "returnSequences": true,
            "dropout": 0,
            "recurrentDropout": 0,
            "useBias": true,
            "unitForgetBias": true
          },
          "inboundNodes": [
            [
              [
                "embedding_1",
                0,
                0,
                []
              ]
            ]
          ]
        },
        {
          "className": "Dropout",
          "config": {
            "name": "dropout_layer_1",
            "trainable": true,
            "rate": 0.2
          },
          "inboundNodes": [
            [
              [
                "lstm_layer_1",
                0,
                0,
                []
              ]
            ]
          ]
        },
        {
          "className": "Dense",
          "config": {
            "name": "dense_layer_1",
            "trainable": true,
            "units": 64,
            "activation": "relu",
            "useBias": true,
            "kernelInitializer": {
              "className": "GlorotUniform",
              "config": {
                "seed": null
              }
            },
            "biasInitializer": {
              "className": "Zeros",
              "config": []
            },
            "kernelRegularizer": {
              "className": "L1L2",
              "config": {
                "l2": 0.0001
              }
            },
            "biasRegularizer": null,
            "activityRegularizer": null
          },
          "inboundNodes": [
            [
              [
                "dropout_layer_1",
                0,
                0,
                []
              ]
            ]
          ]
        },
        {
          "className": "Dropout",
          "config": {
            "name": "dropout_layer_1_1",
            "trainable": true,
            "rate": 0.2
          },
          "inboundNodes": [
            [
              [
                "dense_layer_1",
                0,
                0,
                []
              ]
            ]
          ]
        },
        {
          "className": "Dense",
          "config": {
            "name": "output_layer_1",
            "trainable": true,
            "units": 600,
            "activation": "softmax",
            "useBias": true,
            "kernelInitializer": {
              "className": "GlorotUniform",
              "config": {
                "seed": null
              }
            },
            "biasInitializer": {
              "className": "Zeros",
              "config": []
            },
            "kernelRegularizer": {
              "className": "L1L2",
              "config": {
                "l2": 0.0001
              }
            },
            "biasRegularizer": null,
            "activityRegularizer": null
          },
          "inboundNodes": [
            [
              [
                "dropout_layer_1_1",
                0,
                0,
                []
              ]
            ]
          ]
        }
      ]
    },
    "keras_version": "tfjs-layers 3.21.0",
    "backend": "tensorflow",
    "labelConfig": null,
    "hasLabelInput": false
  },
  "metadata": {
    "type": "single_output",
    "inputShape": [
      null,
      10
    ],
    "outputShape": [
      null,
      600
    ],
    "layerCount": 7,
    "projectId": "33",
    "exportedAt": "2026-07-17T01:21:29.852Z",
    "blockCount": 7,
    "taskId": null,
    "duration": null
  },
  "originalXml": "<xml xmlns=\"https://developers.google.com/blockly/xml\"><block type=\"nn_input\" id=\"*dZ,qf`rpS3!DeFPI6fW\" x=\"56\" y=\"44\"><field name=\"SHAPE\">(None, 10)</field><field name=\"NAME\">input_layer_1</field><next><block type=\"nn_embedding\" id=\"lQ,`]5a@Dne8o9(.9cE=\"><field name=\"INPUT_DIM\">600</field><field name=\"OUTPUT_DIM\">64</field><field name=\"INPUT_LENGTH\">10</field><field name=\"MASK_ZERO\">TRUE</field><field name=\"NAME\">embedding_1</field><next><block type=\"nn_lstm\" id=\"lHKw-!F?YJ5@b)it?H1Y\"><field name=\"UNITS\">64</field><field name=\"ACTIVATION\">tanh</field><field name=\"RECURRENT_ACTIVATION\">sigmoid</field><field name=\"RETURN_SEQUENCES\">TRUE</field><field name=\"DROPOUT\">0</field><field name=\"RECURRENT_DROPOUT\">0</field><field name=\"NAME\">lstm_layer_1</field><next><block type=\"nn_dropout\" id=\"GeQGgsI{{6Vz?R[1w1Rl\"><field name=\"RATE\">0.2</field><field name=\"NAME\">dropout_layer_1</field><next><block type=\"nn_dense\" id=\"FiJ)/Q}jV3?+[gl:2I@E\"><field name=\"UNITS\">64</field><field name=\"ACTIVATION\">relu</field><field name=\"L2_REGULARIZATION\">0.0001</field><field name=\"NAME\">dense_layer_1</field><next><block type=\"nn_dropout\" id=\"{4?_A86kipo5X(#N(xMO\"><field name=\"RATE\">0.2</field><field name=\"NAME\">dropout_layer_1</field><next><block type=\"nn_output\" id=\",x%s)bDRRh_S7y5lTm];\"><field name=\"TASK_TYPE\">classification</field><field name=\"REGRESSION_UNITS\">1</field><field name=\"REGRESSION_ACTIVATION\">linear</field><field name=\"NUM_CLASSES\">600</field><field name=\"CLASSIFICATION_ACTIVATION\">softmax</field><field name=\"L2_REGULARIZATION\">0.0001</field><field name=\"NAME\">output_layer_1</field></block></next></block></next></block></next></block></next></block></next></block></next></block></xml>"
}

二、数据清洗

        如果你使用人名数据集,那么需要进行大规模清洗,保留几千到一万数据即可达到教学效果。但如果训练效果不好,应考虑数据分布问题。一下实验过程的数据是在人名数据集中以固定步长获取的数据,这不是一种好办法,但最终效果没问题。

        把清洗后的数据进一步加工为“姓+等号+名”的形式——默认的序列补全模式分隔符为等号,你可以使用其他字符。然后导入到数据管理器:

        可以看到,模型设置词汇表600盖了近90%的数据,600中有几个作特殊标记,剩余的均为字符,训练器会自动处理这些细节。

三、训练

        导入模型、训练数据,保持默认参数(包括分词器):

        而后,勾选“序列补全模式”,点击“开始训练”即可:

        序列补全模式不会使用滑动窗口来处理数据,输入为多少个数据训练对数就是多少。从上图可以看到大约30-40秒即可训练一轮,训练十轮左右,当模学习进入平台期,即可停止训练并导出已训练模型。

四、预测

        将已训练模型导入到预测器,输入一个姓而后点击“生成文本”:

        多次点击可以生成多个名字,尝试调节控制参数可以使得模型生成产生变化:

        对比输入数据可以看到,模型学会了生成“=”之后的内容——这正是我们想要的,输入一个姓它会生成名并且不仅限于训练数据中该姓对应的名。

        在浏览器内使用本地算力甚至核显就能训练文本生成模型涉及到AiEduLab.tech——AI创想实验室的大量核心技术,暂无公开计划。所以,在演示服务器上不提供该任务类型的训练,我们计划免费(无任何包括后续使用在内的费用)为若干试点中小学搭建局域网服务器,如果您需要加入试点计划可以直接联系我们咨询具体事项。

        在AI创想实验室中,我们无需编程基础,不用学习框架,不用配置环境,无需购买费用高昂的显卡,更不用为云端算力付费,使用当前已有的各种硬件:仅有核显的个人、办公、机房电脑,希沃白板等都能达到理想的教学效果。操作简单但AI核心知识样样俱全,无需师资培训就可以进行教学且能取得理想的教学效果。如果加入试点或合作方那么只需要一台局域网服务器(无需显卡、服务器不用供算力)即可一次投入永久使用全部项目和功能,通过后台管理一分钟即可创建一个本地化、校本化的项目实例。

演示版本地址:www.AiEduLab.tech

有任何问题欢迎留言或发送邮件至:hello@AiEduLab.tech       

更多推荐