from transformers import pipeline, set_seed # 加载GPT-2模型 model_name = "gpt2" nlp = pipeline("text-generation", model=model_name) # 定义微调数据 train_data = [ {"text": "This is the first sentence. ", "new_text": "This is the first sentence. This is the second sentence. "}, {"text": "Another example. ", "new_text": "Another example. This is another sentence. "} ] # 微调模型 nlp_textgen = pipeline("text-generation", model=model_name, tokenizer=model_name, device=0) set_seed(42) nlp_textgen.train(train_data, learning_rate=1e-3, num_train_epochs=1) # 使用微调后的模型生成文本 text = nlp_textgen("Hello, how are you?") print(text)在上面的代码中,我们首先使用pipeline函数加载了GPT-2模型,并将其保存在变量nlp中。然后,我们定义了微调数据train_data,其中包含两个示例。每个示例都包含一个输入文本和一个相应的输出文本。我们将使用这些示例来微调模型。接下来,我们使用pipeline函数再次加载GPT-2模型,并将其保存在变量nlp_textgen中。我们使用set_seed函数设置随机种子,以确保结果可重复。然后,我们使用train函数微调模型,传递train_data数据和一些训练参数(例如学习率和训练轮数)。一旦模型微调完毕,您就可以使用它来生成文本。在上面的示例中,我们使用微调后的模型生成了一段文本,并将其保存在变量text中。然后,我们将文本打印出来以进行查看。
网友回复