用LLM做文本分类,微调选base还是chat

LLM中分类模型和生成模型的本质区别 分类模型** - **架构**:通常基于LLM的基础上,添加特定的分类头(Classification Head),如全连接层。例如,BERT用于文本分类时,会在预训练的Transformer编码器**后接一个线性分类器**。 cls - **参数使用**:仅微调与任务相关的少数参数(如分类头),LLM的主体参数保持冻结。这种方式也被称为"参数高效微调"(Parameter-Efficient Fine-Tuning)。 - **示例**:使用GPT-3.5的Embedding API获取 阅读详情

使用Qwen2ForSequenceClassification实现文本分类任务。

一、实验结果和结论

这几个月,在大模型分类场景做了很多实验,攒了一点小小经验。

1、短文本

1)query情感分类,一般不如BERT

ps:结论和,https://segmentfault.com/a/1190000044485544#item-13,基本一致

2、长文本

1)通话ASR转译长文本,BERT截断512不如LLM

  • LLM没有截断(如果都阶段512,可能效果差不多)

  • 没有对比,BERT进行文本滑动窗口的版本

2)Base v.s. Instruct

  • 数据量小时,Base微调不如Instruct(Instruct模型有对齐税,但是微调数据量小时,效果还是比Base没见过指令微调样本的好)

3)SFT v.s. LoRA

  • 数据量小时(总样本10K以下,每个标签需要视情况而定),SFT微调不如LoRA(SFT调参成本也更大)

3、分类场景的提升方案

1)生成式微调独有

混合同领域相似数据类型不同业务数据,可以提升若干点

  • 数据分布不能差异太大,特别是文本长度,否则混入这种数据反而会让效果下滑(一个平均长度1.2K,一个平均长度5k)

  • 混入比例(接近2:1,不同场景需自行尝试)

  • 混入顺序(我使用的是随机采样,没验证是否分开先后训练顺序是否有影响)

优化提示词(提示词中,增加各类别标签的精要描述;短文本可尝试few-shot)

2)分类头微调 + 生成式微调

  • 数据量大时(10K以上,平均每个标签样本充足),尝试微调Base,而不是微调Instruct

  • 数据增强:尝试无标注数据上跑的伪标签样本(提示词抽的标签 + 微调后的模型抽的标签)

  • 数据量大时,尝试SFT

  • LoRA微调时,加入LLM的embedding层(未验证过)

  • 尝试蒸馏更大模型到小模型(痛点:大模型难调参,训练成本更高,部署上线还是得小模型)

  • 尝试LoRA的变体

  • 尝试调参(试过optuna自动搜索,效果也不太好;一般就调lr, epoch, rank)

3)重量级

Base模型,领域数据增量预训练后,再进行指令微调

  • 方案待验证 (若验证成功,其好处是训出来的基座在各个领域任务上的微调都能提点)

  • 这边尝试了在Qwen2-7B-Instruct的领域数据指令微调后的模型,微调效果反而比直接微调Qwen2-7B-Instruct效果差些。由于不清楚该模型训练步骤细节,所以原因尚不明确)

第一优先级,还是搞数据。其次,才是尝试各种方案的加加减减。

4、注意点

  • 学习率:训练的参数量越大,学习率适当要调小

  • 标签噪声:样本标注错误,需要在错误分析时进行剔除和校正

  • 分类业务规则:复杂场景,需要提前确定好完备的标注规则,避免返工(那些模型可以做,那么模型不能做)

待改进点:

  • 文本动态Padding

  • 分类头多标签版本效果未验证成功

二、文本分类-从BERT到LLM

Qwen2ForSequenceClassification和LlamaForSequenceClassification,以及BERTForSequenceClassification,都可以用来完成文本分类任务。

都可以通过HuggingFace transformers的AutoModelForSequenceClassification库,自动加载相应的模型类,进行序列分类任务。

Qwen2ForSequenceClassification和BERTForSequenceClassification,逻辑上是一致的。都是在模型的输出层,加上一个Linear层,用来完成分类任务。

之前在,BERT上做的所有改动,都可以迁移到LLM上。譬如,BERT-CRF、BERT-SUM。

2.1 BERTForSequenceClassification

BertForSequenceClassification是一个已经实现好的用来进行文本分类的类,继承自BertPreTrainedModel,一般用来进行文本分类任务。

通过num_labels传递分类的类别数,从构造函数可以看出这个类大致由3部分组成,1个是BertModel,1个是Dropout,1个是用于分类的线性分类器Linear。

class BertForSequenceClassification(BertPreTrainedModel):       def __init__(self, config):           super(BertForSequenceClassification, self).__init__(config)           self.num_labels = config.num_labels   python           self.bert = BertModel(config)           self.dropout = nn.Dropout(config.hidden_dropout_prob)           self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)           self.init_weights()   

Bert用于提取文本特征进行Embedding,Dropout防止过拟合,Linear是一个弱分类器,进行分类,如果需要用更复杂的网络结构进行分类可以参考它进行改写。

forward()函数里面已经定义了损失函数,训练时可以不用自己额外实现,返回值包括4个内容

def forward(...):       ...       if labels is not None:           if self.num_labels == 1:               #  We are doing regression               loss_fct = MSELoss()               loss = loss_fct(logits.view(-1), labels.view(-1))           else:               loss_fct = CrossEntropyLoss()               loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))           outputs = (loss,) + outputs       return outputs  # (loss), logits, (hidden_states), (attentions)   

2.2 Qwen2ForSequenceClassification

接下来。看看Qwen2ForSequenceClassification。

Qwen2ForSequenceClassification(     (model): Qwen2Model(       (embed_tokens): Embedding(151936, 1024, padding_idx=151643)       (layers): ModuleList(         (0-23): 24 x Qwen2DecoderLayer(           (self_attn): Qwen2SdpaAttention(             (q_proj): Linear(in_features=1024, out_features=1024, bias=True)             (k_proj): Linear(in_features=1024, out_features=1024, bias=True)             (v_proj): Linear(in_features=1024, out_features=1024, bias=True)             (o_proj): Linear(in_features=1024, out_features=1024, bias=False)             (rotary_emb): Qwen2RotaryEmbedding()           )           (mlp): Qwen2MLP(             (gate_proj): Linear(in_features=1024, out_features=2816, bias=False)             (up_proj): Linear(in_features=1024, out_features=2816, bias=False)             (down_proj): Linear(in_features=2816, out_features=1024, bias=False)             (act_fn): SiLU()           )           (input_layernorm): Qwen2RMSNorm()           (post_attention_layernorm): Qwen2RMSNorm()         )       )       (norm): Qwen2RMSNorm()     )     (score): Linear(in_features=1024, out_features=3, bias=False)   )   

Qwen2官方代码实现,内置三种模式:

single_label_classification 单标签分类

  • 损失为CrossEntropyLoss

  • 取单标签对应logit,算负对数似然

multi_label_classification 多标签分类

  • 损失为BCEWithLogitsLoss

  • 标签为muilti-hot, 预测logits计算sigmoid,实际取对应维度标签Logit,损失求和

regression 回归

  • 损失为MSELoss

  • 默认为单维度回归(回归可以作为奖励模型,预测打分)

这3种模式的输入标签不同。

`class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):       def __init__(self, config):           super().__init__(config)           self.num_labels = config.num_labels           self.model = Qwen2Model(config)           self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)              # Initialize weights and apply final processing           self.post_init()          def get_input_embeddings(self):           return self.model.embed_tokens          def set_input_embeddings(self, value):           self.model.embed_tokens = value          @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)       def forward(           self,           input_ids: torch.LongTensor = None,           attention_mask: Optional[torch.Tensor] = None,           position_ids: Optional[torch.LongTensor] = None,           past_key_values: Optional[List[torch.FloatTensor]] = None,           inputs_embeds: Optional[torch.FloatTensor] = None,           labels: Optional[torch.LongTensor] = None,           use_cache: Optional[bool] = None,           output_attentions: Optional[bool] = None,           output_hidden_states: Optional[bool] = None,           return_dict: Optional[bool] = None,       ) -> Union[Tuple, SequenceClassifierOutputWithPast]:           r"""           labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):               Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,               config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If               `config.num_labels > 1` a classification loss is computed (Cross-Entropy).           """           return_dict = return_dict if return_dict is not None else self.config.use_return_dict              transformer_outputs = self.model(               input_ids,               attention_mask=attention_mask,               position_ids=position_ids,               past_key_values=past_key_values,               inputs_embeds=inputs_embeds,               use_cache=use_cache,               output_attentions=output_attentions,               output_hidden_states=output_hidden_states,               return_dict=return_dict,           )           hidden_states = transformer_outputs[0]           logits = self.score(hidden_states)              if input_ids is not None:               batch_size = input_ids.shape[0]           else:               batch_size = inputs_embeds.shape[0]              if self.config.pad_token_id is None and batch_size != 1:               raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")           if self.config.pad_token_id is None:               sequence_lengths = -1           else:               if input_ids is not None:                   # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility                   sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1                   sequence_lengths = sequence_lengths % input_ids.shape[-1]                   sequence_lengths = sequence_lengths.to(logits.device)               else:                   sequence_lengths = -1              pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]              loss = None           if labels is not None:               labels = labels.to(logits.device)               if self.config.problem_type is None:                   if self.num_labels == 1:                       self.config.problem_type = "regression"                   elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):                       self.config.problem_type = "single_label_classification"                   else:                       self.config.problem_type = "multi_label_classification"                  if self.config.problem_type == "regression":                   loss_fct = MSELoss()                   if self.num_labels == 1:                       loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())                   else:                       loss = loss_fct(pooled_logits, labels)               elif self.config.problem_type == "single_label_classification":                   loss_fct = CrossEntropyLoss()                   loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))               elif self.config.problem_type == "multi_label_classification":                   loss_fct = BCEWithLogitsLoss()                   loss = loss_fct(pooled_logits, labels)           if not return_dict:               output = (pooled_logits,) + transformer_outputs[1:]               return ((loss,) + output) if loss is not None else output              return SequenceClassifierOutputWithPast(               loss=loss,               logits=pooled_logits,               past_key_values=transformer_outputs.past_key_values,               hidden_states=transformer_outputs.hidden_states,               attentions=transformer_outputs.attentions,           )   `

三、LoRA微调 Qwen2ForSequenceClassification

在LoRA微调后,将合并LoRA权重,并存储模型。 因为,目前PEFT代码没有,把分类头Linear层的参数存储下来。只靠LoRA权重无法,复现训练的Qwen2ForSequenceClassification模型。

有需要可以小改下代码

这边在modelscope提供的环境,完成了代码的测试。

from modelscope import AutoModelForCausalLM, AutoTokenizer      model_name_or_path = "qwen/Qwen2.5-3B-Instruct"   model = AutoModelForCausalLM.from_pretrained(     model_name_or_path,     torch_dtype="auto",     device_map="auto"   )      tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)   prompt = "不想学习怎么办?有兴趣,但是拖延症犯了"   messages = [       {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},       {"role": "user", "content": prompt}   ]   text = tokenizer.apply_chat_template(       messages,       tokenize=False,       add_generation_prompt=True   )   model_inputs = tokenizer([text], return_tensors="pt").to(model.device)      generated_ids = model.generate(       **model_inputs, max_new_tokens=512   )   generated_ids = [       output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)   ]      response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]   ```shell   Downloading [config.json]: 100%|██████████| 661/661 [00:00<00:00, 998B/s]   Downloading [configuration.json]: 100%|██████████| 2.00/2.00 [00:00<00:00, 2.30B/s]   Downloading [generation_config.json]: 100%|██████████| 242/242 [00:00<00:00, 557B/s]   Downloading [LICENSE]: 100%|██████████| 7.21k/7.21k [00:00<00:00, 11.7kB/s]   Downloading [merges.txt]: 100%|██████████| 1.59M/1.59M [00:00<00:00, 3.01MB/s]   Downloading [model-00001-of-00002.safetensors]: 100%|██████████| 3.70G/3.70G [00:10<00:00, 373MB/s]    Downloading [model-00002-of-00002.safetensors]: 100%|██████████| 2.05G/2.05G [00:06<00:00, 332MB/s]    Downloading [model.safetensors.index.json]: 100%|██████████| 34.7k/34.7k [00:00<00:00, 56.8kB/s]   Downloading [README.md]: 100%|██████████| 4.79k/4.79k [00:00<00:00, 10.3kB/s]   Downloading [tokenizer.json]: 100%|██████████| 6.71M/6.71M [00:00<00:00, 8.58MB/s]   Downloading [tokenizer_config.json]: 100%|██████████| 7.13k/7.13k [00:00<00:00, 13.8kB/s]   Downloading [vocab.json]: 100%|██████████| 2.65M/2.65M [00:00<00:00, 5.09MB/s]   /usr/local/lib/python3.10/site-packages/accelerate/utils/modeling.py:1405: UserWarning: Current model requires 234882816 bytes of buffer for offloaded layers, which seems does not fit any GPU's remaining memory. If you are experiencing a OOM later, please consider using offload_buffers=True.     warnings.warn(   

面对兴趣与拖延之间的矛盾,确实会让人感到困扰。这里有一些建议或许能帮助你克服拖延,更好地坚持学习:

  1. 设定小目标:将大目标分解为一系列小目标。完成每一个小目标都是一次小小的胜利,这可以增加你的动力和成就感。

  2. 制定计划:为自己规划一个详细的学习计划,并尽量按照计划执行。记得为休息时间留出空间,保持良好的工作与休息平衡。

  3. 保持积极心态:对自己保持耐心和理解,不要因为一时的困难而放弃。记住,进步的过程就是成长的过程。

由于modelscope不支持LORA, 这边查看了本地路径

print(model.model_dir)      /mnt/workspace/.cache/modelscope/hub/qwen/Qwen2___5-3B-Instruct   

查看文件

config.json        merges.txt               README.md   configuration.json     model-00001-of-00002.safetensors     tokenizer_config.json   generation_config.json     model-00002-of-00002.safetensors     tokenizer.json   LICENSE            model.safetensors.index.json         vocab.json   huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...   

微调代码

### 初始化设定和随机种子   import os   os.environ["CUDAVISIBLE_DEVICES"] = "0"      import torch   import numpy as np   import pandas as pd   import random      seed = 42   random.seed(seed)   np.random.seed(seed)   torch.manual_seed(seed)   torch.cuda.manual_seed(seed)   torch.backends.cudnn.deterministic = True   torch.backends.cudnn.benchmark = False   

基于prompt用大模型构造了20个样本。

import json      x = '''这基金表现也太差了吧,买了半年了还亏着呢。   管理费收得比别的基金都高,感觉就是在给基金公司打工。   想查查具体投了啥,结果发现透明度低得要命,啥也看不清楚。   基金经理换来换去的,都不知道到底谁在管我的钱。   客服电话打过去半天才有人接,问个问题还得等上好几天才有回复。   市场稍微有点风吹草动,这基金就跌得比谁都快。   投资组合里全是同一行业的股票,风险大得让人睡不着觉。   长期持有也没见赚多少钱,还不如存银行定期。   分红政策一会儿一个样,根本没法做财务规划。   当初宣传时说得好听,实际操作起来完全不是那么回事。'''   x_samples = x.split("\n")      y = '''这基金真的稳啊,买了之后收益一直挺不错的,感觉很靠谱!   管理团队超级专业,每次市场波动都能及时调整策略,让人放心。   透明度很高,随时都能查到投资组合的情况,心里有数。   基金经理经验老道,看准了几个大机会,赚了不少。   客服态度特别好,有问题总能很快得到解答,服务真是没得说。   即使在市场不好的时候,这基金的表现也比大多数同类产品强。   分散投资做得很好,风险控制得很到位,睡个安稳觉没问题。   长期持有的话,回报率真的非常可观,值得信赖。   分红政策明确而且稳定,每年都能按时收到分红,计划财务很方便。   宣传时承诺的那些好处都实现了,真心觉得选对了这只基金。'''   y_samples = y.split("\n")      # 创建一个Python字典   x_data = [{"content": i, "label": 0, "标注类别": "正向"} for i in x_samples]   y_data = [{"content": i, "label": 1, "标注类别": "负向"} for i in y_samples]         def save_json(path, data):       # 将Python字典转换为JSON字符串       with open(path, 'w', encoding='utf-8') as f:           json.dump(data, f, ensure_ascii=False, indent=4)         save_json('data/classify_train.json', x_data[:6]+y_data[:6])   save_json('data/classify_valid.json', x_data[6:8]+y_data[6:8])   save_json('data/classify_test.json', x_data[8:]+y_data[8:])   

数据加载

import json   from tqdm import tqdm   from loguru import logger   from datasets import Dataset, load_dataset      def get_dataset_from_json(json_path, cols):       with open(json_path, "r") as file:           data = json.load(file)           df = pd.DataFrame(data)       dataset = Dataset.from_pandas(df[cols], split='train')       return dataset         # load_dataset加载json的dataset太慢了   cols = ['content', 'label', '标注类别']   train_ds = get_dataset_from_json('data/classify_train.json', cols)   logger.info(f"TrainData num: {len(train_ds)}")   valid_ds = get_dataset_from_json('data/classify_valid.json', cols)   logger.info(f"ValidData num: {len(valid_ds)}")   test_ds = get_dataset_from_json('data/classify_test.json', cols)   logger.info(f"TestData num: {len(test_ds)}")   
print(train_ds[0])      {'content': '这基金表现也太差了吧,买了半年了还亏着呢。', 'label': 0, '标注类别': '正向'}   

准备dataset(简单实现截断和padding, 无动态padding)

id2label = {0: "正向", 1: "负向"}   label2id = {v:k for k,v in id2label.items()}      from transformers import AutoTokenizer, DataCollatorWithPadding   # from modelscope import AutoTokenizer, DataCollatorwithPadding      model_name_or_path = "/mnt/workspace/.cache/modelscope/hub/qwen/Qwen2___5-3B-Instruct"   model_name = model_name_or_path.split("/")[-1]   print(model_name)      tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, padding_side='left')   tokenizer.add_special_tokens({'pad_token': '<|endoftext|>'})   data_collator = DataCollatorWithPadding(tokenizer=tokenizer)      MAX_LEN = 24   txt_colname = 'content'      def preprocess_function(examples):       # padding后处理效率不高,需要动态batch padding       return tokenizer(examples[txt_colname], max_length=MAX_LEN, padding=True, truncation=True)      tokenized_train = train_ds.map(preprocess_function, num_proc=64, batched=True)   tokenized_valid = valid_ds.map(preprocess_function, num_proc=64, batched=True)   

sklearn评测代码

from sklearn.metrics import (       classification_report,       confusion_matrix,       accuracy_score,       f1_score,       precision_score,       recall_score   )      def evals(test_ds, model):       k_list = [x[txt_colname] for x in test_ds]       model.eval()          k_result = []       for idx, txt in tqdm(enumerate(k_list)):           model_inputs = tokenizer([txt], max_length=MAX_LEN, truncation=True, return_tensors="pt").to(model.device)           logits = model(**model_inputs).logits           res = int(torch.argmax(logits, axis=1).cpu())           k_result.append(id2label.get(res))          y_true = np.array(test_ds['label'])       y_pred = np.array([label2id.get(x) for x in k_result])       return y_true, y_pred      def compute_metrics(eval_pred):       predictions, label = eval_pred       predictions = np.argmax(predictions, axis=1)       return {"f1": f1_score(y_true=label, y_pred=predictions, average='weighted')}      def compute_valid_metrics(eval_pred):       predictions, label = eval_pred       y_true, y_pred = label, predictions       accuracy = accuracy_score(y_true, y_pred)       print(f'Accuracy: {accuracy}')       metric_types = ['micro', 'macro', 'weighted']       for metric_type in metric_types:           precision = precision_score(y_true, y_pred, average=metric_type)            recall = recall_score(y_true, y_pred, average=metric_type)           f1 = f1_score(y_true, y_pred, average=metric_type)           print(f'{metric_type} Precision: {precision}')           print(f'{metric_type} Recall: {recall}')           print(f'{metric_type} F1 Score: {f1}')   

模型加载,使用Trainer进行训练

import torch   from transformers import AutoModelForSequenceClassification   from transformers import Trainer, TrainingArguments   from peft import get_peft_config, PeftModel, PeftConfig, get_peft_model, LoraConfig, TaskType      rank = 64   alpha = rank*2   training_args = TrainingArguments(       output_dir=f"./output/{model_name}/seqence_classify/",       learning_rate=5e-5,       per_device_train_batch_size=8,       per_device_eval_batch_size=4,       num_train_epochs=3,       weight_decay=0.01,       evaluation_strategy="epoch",       save_strategy="epoch",       load_best_model_at_end=True   )      peft_config = LoraConfig(       task_type=TaskType.SEQ_CLS,       target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],       inference_mode=False,       r=rank,       lora_alpha=alpha,       lora_dropout=0.1   )      model = AutoModelForSequenceClassification.from_pretrained(       model_name_or_path,       num_labels=len(id2label),       id2label=id2label,       label2id=label2id,       torch_dtype=torch.bfloat16,       device_map="auto",       trust_remote_code=True,       attn_implementation="flash attention2"   )      model.config.pad_token_id = tokenizer.pad_token_id      model = get_peft_model(model, peft_config)   model.print_trainable_parameters()      trainer = Trainer(       model=model,       args=training_args,       train_dataset=tokenized_train,       eval_dataset=tokenized_valid,       tokenizer=tokenizer,       data_collator=data_collator,       compute_metrics=compute_metrics   )   logger.info(f"start Trainingrank: {rank}")   trainer.train()      logger.info(f"Valid Set, rank: {rank}")   y_true, y_pred = evals(valid_ds, model)   metrics = compute_valid_metrics((y_pred, y_true))   logger.info(metrics)      logger.info(f"Test Set, rank: {rank}")   y_true, y_pred = evals(test_ds, model)   metrics = compute_valid_metrics((y_pred, y_true))   logger.info(metrics)      saved_model = model.merge_and_unload()   saved_model.save_pretrained('/model/qwen2-3b/seqcls')   

将LoraConfig和get_peft_model去掉,就是SFT的代码。

model的结构

PeftModelForSequenceClassification(     (base_model): LoraModel(       (model): Qwen2ForSequenceClassification(         (model): Qwen2Model(           (embed_tokens): Embedding(151936, 2048)           (layers): ModuleList(             (0-35): 36 x Qwen2DecoderLayer(               (self_attn): Qwen2SdpaAttention(                 (q_proj): Linear(in_features=2048, out_features=2048, bias=True)                 (k_proj): Linear(in_features=2048, out_features=256, bias=True)                 (v_proj): Linear(in_features=2048, out_features=256, bias=True)                 (o_proj): Linear(in_features=2048, out_features=2048, bias=False)                 (rotary_emb): Qwen2RotaryEmbedding()               )               (mlp): Qwen2MLP(                 (gate_proj): Linear(in_features=2048, out_features=11008, bias=False)                 (up_proj): Linear(in_features=2048, out_features=11008, bias=False)                 (down_proj): Linear(in_features=11008, out_features=2048, bias=False)                 (act_fn): SiLU()               )               (input_layernorm): Qwen2RMSNorm((2048,), eps=1e-06)               (post_attention_layernorm): Qwen2RMSNorm((2048,), eps=1e-06)             )           )           (norm): Qwen2RMSNorm((2048,), eps=1e-06)         )         (score): Linear(in_features=2048, out_features=2, bias=False)       )     )   )   

预测

txt = "退钱,什么辣鸡基金"   model_inputs = tokenizer([txt], max_length=MAX_LEN, truncation=True, return_tensors="pt").to(saved_model.device)   logits = saved_model(**model_inputs).logits   res = int(torch.argmax(logits, axis=1).cpu())   print(id2label[res])      负向   

output输出类型

SequenceClassifierOutputWithPast(loss=None, logits=tensor([[-0.1387,  2.3438]], device='cuda:0', grad_fn=<IndexBackward0>), past_key_values=((tensor([[[[ -3.3750,   0.3164,   2.3125,  ...,  56.5000,  26.0000,  87.0000],             [ -4.6875,   3.0312,   0.6875,  ...,  57.7500,  24.3750,  86.0000],             [ -0.7109,   1.1094,  -0.7383,  ...,  56.7500,  24.8750,  86.5000],             ...,             ...,             [-0.2188,  0.2148,  0.4375,  ..., -0.1016,  0.9336, -1.1016],             [ 1.3281,  0.3359,  1.3125,  ..., -0.3906,  0.0312, -0.0391],             [ 0.8789,  0.5312,  1.4297,  ...,  0.1797, -0.9609, -0.6445]]]],          device='cuda:0'))), hidden_states=None, attentions=None)   

跑测结果

Some weights of Qwen2ForSequenceClassification were not initialized from the model checkpoint at /mnt/workspace/.cache/modelscope/hub/qwen/Qwen2___5-3B-Instruct and are newly initialized: ['score.weight']   You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.   Detected kernel version 4.19.91, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.   2024-10-09 23:54:07.615 | INFO     | __main__:<module>:53 - start Trainingrank: 64   trainable params: 119,738,368 || all params: 3,205,681,152 || trainable%: 3.7352   [6/6 00:08, Epoch 3/3]   Epoch   Training Loss   Validation Loss F1   1   No log  0.988281    0.333333   2   No log  0.527344    0.733333   3   No log  0.453125    1.000000   2024-10-09 23:54:17.371 | INFO     | __main__:<module>:56 - Valid Set, rank: 64   4it [00:00,  8.03it/s]   2024-10-09 23:54:17.896 | INFO     | __main__:<module>:59 - None   2024-10-09 23:54:17.897 | INFO     | __main__:<module>:61 - Test Set, rank: 64   Accuracy: 1.0   micro Precision: 1.0   micro Recall: 1.0   micro F1 Score: 1.0   macro Precision: 1.0   macro Recall: 1.0   macro F1 Score: 1.0   weighted Precision: 1.0   weighted Recall: 1.0   weighted F1 Score: 1.0   4it [00:00, 13.58it/s]      2024-10-09 23:54:18.218 | INFO     | __main__:<module>:64 - None   Accuracy: 0.75   micro Precision: 0.75   micro Recall: 0.75   micro F1 Score: 0.75   macro Precision: 0.8333333333333333   macro Recall: 0.75   macro F1 Score: 0.7333333333333334   weighted Precision: 0.8333333333333333   weighted Recall: 0.75   weighted F1 Score: 0.7333333333333334   

四、自测结果

4.1 短文本

常用的对话中,客户的单轮query, 情感极性分类。

3分类,长度最大128字,训练样本量6K左右

query ,比不过基础的BERT      Accuracy:0.9334389857369255   microPrecision:0.9334389857369255   microRecall:0.9334389857369255   micro F1Score:0.9334389857369255   macro Precision:0.9292774942877138   macro Reca1l:0.9550788300142491   macro F1Score:0.9388312342456646   weightedPrecision:0.9418775412386249   weighted Recall:0.9334389857369255   weighted F1Score:0.93383533375322       precision recall fi-score support   0 1.00 0.88 0.93 334   1 0.94 0.99 0.97 101   2 0.85 0.99 0.92 196   accuracy 0.93   macro avg 0.93   weightedavg 0.94   

使用Chinese-RoBerta-large-wwm,及其各种变体进行比较。7B、3B、1.5B和0.5B,均无优势。比不过Large、Base。一些裁减参数量就几十M的都能到85左右,所以看不出LLM的优势。

结论:

短文本场景,LLM的优势在于少样本、样本不均匀,以及基于prompt+fewshot用72B规模生成伪标签。

除非样本量上万,且价值比较大的场景,可以尝试14B以上模型,调参确认提点后,再进行蒸馏。

绝大部分短文本场景没有必要用到大模型,除非是生成场景,比如query扩写、query多轮改写。

4.2 长文本

这里用到的是ASR转译文本

训练集4918样本,平均长度740字,最大4631字,75% 918字

LoRA微调结果,一般2个epoch效果好些,rank要适当调参。

epoch=1, rank=96, alpha=2*rank

Accuracy:0.8415637860082305   micro Precision:0.8415637860082305    micro Recall:0.8415637860082305   micro F1 Score:0.8415637860082305   macro Precision:0.8075007129137883   macro Recall: 0.770659344467927   macroF1 Score:0.7726373117446225   weightedPrecision:0.8509932419375813   weighted Recall:0.8415637860082305   weighted F1Score:0.8420807262647815       precision recall f1-score support   0 0.95 0.83 0.89 163   1 0.76 0.77 0.77 66   2 0.78 0.89 0.83 63   3 0.81 0.81 0.81 42   4 0.80 0.93 0.86 30   5 0.48 0.56 0.51 18   6 1.00 0.43 0.60 7   7 0.88 0.95 0.92 97   

epoch=3,rank=96, alpha=2*rank

Accuracy:0.8847736625514403   micro Precision:0.8847736625514403   micro Recall:0.8847736625514403   micro F1 Score:0.8847736625514403    macro Precision:0.8765027065399982   macroRecall:0.8400805218716799   macro F1 Score:.8527883278910355   weighted Precision:0.8903846924862034   weighted Recall:0.8847736625514403   weighted F1 Score:0.8852820009557909       precision recall fl-score support   0 0.94 0.89 0.91 163   1 0.77 0.85 0.81 66   2 0.81 0.88 0.83 42   3 0.79 0.90 0.86 63   4 1.00 0.93 0.97 30   5 0.92 0.61 0.73 18   6 0.83 0.71 0.77 7   7 0.96 0.94 0.95 97   

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范
  • …

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署
  • …

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建
  • …

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案
  • …

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】

在这里插入图片描述

ML307C OPENCPU开发环境搭建完整指南:从零到跑通 在物联网通信方案中,Cat.1模组凭借适中的速率、低成本和成熟的网络覆盖,成为共享设备、支付终端及定位追踪等领域的热门选择。传统方案通常采用外置MCU通过AT指令控制模组,但硬件成本与开发复杂度较高。OPENCPU模式直接将应用代码运行于模组内置处理器,省去外部MCU,降低物料清单并简化系统结构,同时保留RTOS实时任务调度能力。开发者可以像操作单片机一样管理GPIO、串口与网络协议栈,适用于业务逻辑不复杂的联网产品。然而,实际搭建ML307C的OPENCPU开发环境涉及工具链配置、SDK导入、镜像编译与烧 阅读详情

相关推荐

【机器人】线性方程最小二乘解法对机械臂DH参数进行标定

1.前言 看了一篇文章,觉得里面的DH参数标定法讲的很清晰,便使用Matlab复现了一下,效果还可以,特写此文记录。 2.原理 2.1.误差最佳值的最小二乘计算 有研究结果表明:几乎95%的机器人位置误差都是由机器人内部运动学的不准确描述引起的,所以对DH模型参数进行标定是很有必要的。 DH参数物理含义:选自《机器人学、机器视觉与控制-Matlab基础》 当DH参数确定后,我们...

要恰饭得嘛 1万+

全面解读大模型LLM的微调

在快速发展的人工智能领域中,有效地利用大型语言模型(LLM)变得越来越重要。然而,有许多不同的方式可以使用大型语言模型,这可能会让我们感到困惑。实际上,可以使用预训练的大型语言模型进行新任务的上下文学习并进行微调。

Y525698136的博客 1133

NVIDIA显卡在Linux下的功率限制问题:RTX 3060 Laptop的解决方案与避坑指南

本文针对NVIDIA RTX 3060 Laptop显卡在Linux系统下遭遇功率限制的问题,提供了详细的诊断与解决方案。通过使用nvidia-smi工具监控显卡状态,并重点介绍了通过升级驱动、启用nvidia-powerd服务来激活Dynamic Boost 2.0功能,从而安全、智能地解锁额外显卡功率,有效提升性能。

weixin_29290947的博客 663

从基础到精通:构建并微调大型语言模型以实现分类任务

尝试微调第一个输出 token。注意与微调最后一个输出 token 相比,预测性能的变化。

2401_85390073的博客 3733

【游戏开发】初识寻路&navmesh,探索RecastDemo

在手游时代,尤其对于大世界游戏而言,寻路的实现基本在专门的寻路服务器上进行。在众多寻路的解决方案中,recastnavigation是最为经典实用的一个,很多游戏甚至游戏引擎都采用类似的实现。recastnavigation项目自带了RecastDemo,用图形化的界面帮助用户认识寻路网格(navmesh)的生成以及寻路的过程。因此,作为初学者的笔者,也决定通过RecastDemo去初步认识寻路的机理奥秘。 构建RecastDemo 首先克隆recastnavigation项目,从文档中可以看到Recast

HiKariのTechLab 3061

筹码峰五句口诀,看懂主力的秘密动作!(附实战图示)

筹码图的价值在于,它不像K线那样容易造假。主力可以骗线,但骗不了筹码分布。主力在不在;是吸筹还是出货;接下来是变盘还是震荡。这五句口诀可以说是“筹码阅读的入门圣经”:单峰坚挺变盘在即,双峰对垒高抛低吸;上峰不移主力在跑,多峰林立行情不止;下峰不移不离不弃,筹码识庄稳中取利!📌市场从来不是靠猜,而是靠看清。筹码,就是主力最真实的痕迹。如果你想学会提前布局、跟庄不被甩,学会看筹码峰——这一步必须打牢!

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1188

llms 文本分类的微调

LLMS文本分类

一休 1367

YOLOv11 改进 - 特征融合 | 小目标检测救星:DySample动态上采样减少特征丢失

本文介绍了超轻量且高效的动态上采样器DySample与YOLOv11的结合,以解决传统上采样器工作负载大、应用场景受限的问题。DySample从点采样角度构建上采样,绕过动态卷积,使用PyTorch标准内置函数实现,无需定制CUDA包,能大幅减少参数、FLOPs等资源消耗。我们将DySample代码集成进YOLOv11。实验脚本显示,结合DySample的YOLOv11在多个密集预测任务中或表现出色。

魔改工程师的博客 1441

【NLP实战-BERT文本分类】一文搞懂基于BERT进行文本分类并定制化评估指标

文本分类任务的目标是将文本数据分配到预定义的类别中。在本次项目中,我们使用了一个包含用户评论和评价维度的数据集。数据集中的每条评论都对应一个评价维度(如“服务态度”、“产品质量”等),我们的目标是训练一个模型,能够自动根据评论内容预测其对应的评价维度。

志在创建优质博客、通俗易懂、助力大家提高学习效率! 1296

csp信奥赛C++标准模板库STL案例应用1

csp信奥赛C++标准模板库STL案例应用1

王老师青少年编程 1391

r -括号[ ]和双括号[[ ]]之间的差异

这与我们试图在屏幕上显示r的值时完全相同,这意味着使用单括号返回了一个列表,其中在索引1处,我们有一个10个元素的向量,然后我们有两个名为foo和far的元素。另一方面,双括号将只返回列表中的一个元素。在这个例子中,我们给出了一个索引“1”,作为回报,我们得到了一个包含一个元素的列表(这是一个包含10个数字的数组)-单括号会给我们一个列表。简而言之,单个括号将始终返回另一个列表,其元素数等于传递到单个括号中的元素数或索引数。在这个例子中,我们传递了一个元素的名称,作为回报,返回了一个包含一个元素的列表。

Mrrunsen的博客 2180

LLM文本分类微调,Base和Chat谁更胜一筹?

使用Qwen2ForSequenceClassification实现文本分类任务。

AI前沿技术的分享! 957

vue3:最新实现腾讯人脸核身+增强版人脸核身使用方法及示例源码,Vue3如何使用腾讯云慧眼人脸核身,提供人脸核身案例、身份信息核验、活体检测与核身比对等示例代码(后端spring与thinkphp)

vue3接入腾讯人脸核身,腾讯云人脸核身Vue3+后端代码,H5人脸核身,vue3 H5如何使用腾讯人脸核身sdk,vue3+thinkphp腾讯人脸核身,Spring Boot接入腾讯云人脸核身教程,hinkphp腾讯人脸核身,vue3人脸核身插件接入流程,vue+spring boot实现腾讯人脸核身,vue3接入腾讯云【增强版人脸核身接入】,vue3 h5微信公众号网页腾讯云慧眼人脸核身,tvue3接入人脸核身SDK,vue3+typescrip+vite接入慧眼实名认证,vue3腾讯云活体人脸核身(

✅ 精选推荐文章 4130

DeepSeek-LLM Base模型与Chat模型:差在哪,一次讲清怎么选

直接给结论:要聊天、问问题、写代码,选 DeepSeek-LLM-67B-Chat;要拿自己的数据微调出行业模型,选 DeepSeek-LLM-67B-Base。两者架构相同,差别只在训练流程的后半段。 ## 先说结论 判断标准很朴素:生成类任务(数学、代码、遵循指令)看 Chat,知识问答类任务看 Base。官方评测里,GSM8K 数学题 Chat 模型 **84.1%**、Base 模型

gitblog_01000的博客 411

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

深度解析:DeepSeek LLM Base模型与Chat模型技术选型完全指南

在人工智能技术快速发展的今天,大型语言模型已成为企业数字化转型和产品创新的核心驱动力。DeepSeek LLM作为开源社区的重要贡献,提供了67B和7B两种规模的Base与Chat模型变体,为技术决策者提供了灵活的选择空间。本文将深入分析这两种模型的技术差异、性能表现和适用场景,帮助您做出明智的技术选型决策。 ## 问题分析:模型定位与核心能力差异 ### Base模型的技术定位与核心优势 D

gitblog_00778的博客 792

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

DeepSeek-LLM版本对比:Base模型与Chat模型核心差异解析

还在为选择哪个DeepSeek-LLM版本而困惑?一文帮你彻底搞懂Base模型与Chat模型的本质区别! 通过本文,你将获得: - Base模型与Chat模型的精准定位差异 - 两种模型在各项基准测试中的表现对比 - 实际应用场景选择建议 - 性能与效率的权衡考量 ## 🔍 模型定位与训练目标差异 **Base模型**(如DeepSeek-LLM-67B-Base](https://lin

gitblog_01083的博客 1350

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

DeepSeek-LLM Base 模型与 Chat 模型怎么选:一份基于评测数据的选型说明

结论先说:如果你的产出要直接给终端用户看——对话、客服、问答助手——选 DeepSeek-LLM 的 Chat 模型;如果你要拿模型继续做二次微调,或者任务只是纯文本补全这类非对话场景,选 DeepSeek-LLM 的 Base 模型。两者的本质区别在于训练流水线上的位置:Base 是纯预训练的产物,只学会了"预测下一个词";Chat 在 Base 之上又经过指令微调和安全对齐,学会了"按人类对话

gitblog_01032的博客 200

如何选对 DeepSeek-LLM 的 Base 与 Chat:7B / 67B 选型指南与关键数据

准备用 DeepSeek-LLM 搭一个问答服务,打开模型列表才发现有 7B、67B,还各分 Base 和 Chat 四个版本——选错版本,轻则答非所问,重则显存直接爆掉。DeepSeek-LLM 是 DeepSeek 从零训练的 67B 参数开源语言模型(同时提供 7B),在 2 万亿中英文 token 上预训练,并开放了全部四个权重文件,官方仓库位于 gitcode.com/GitHub_Tr

gitblog_00715的博客 1043

DeepSeek-LLM 67B 完整指南:Base 模型与 Chat 模型一文讲透

当你下载 DeepSeek LLM 时,大概率会懵:同一个 67B,怎么有 Base 和 Chat 两个版本?同样一个问题,两者的回答可能差出十万八千里。到底该装哪个? ## 🧭 读完你能带走 - 一句话说清 Base 与 Chat 的训练目标差异,不再对着模型名发呆 - 拿一份 67B 双版本基准数据对照表,看懂数学、代码、中文各自的胜负手 - 得到一份"你更适合哪个"的场景清单,对号入座

gitblog_00316的博客 226
上一篇: 【RAG实战】Prompting vs. RAG vs. Finetuning: 如何选择LLM应用选择最佳方案
下一篇: 生成式人工智能(GenAI)开发者必读15篇关键论文全解析
Python_金钱豹
博客等级 码龄5年 1万+粉丝 2860原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址