Lesson 75 Uncomfortable shoes

Lesson 75 Uncomfortable shoes

词汇

ago ad. 以前——过去式符号
搭配:long long ago 很久很久以前
   = long time ago
   = once upon a time
例句:很久很久以前,他很瘦。
   Long long ago, he was very thin.

buy v. 买 过去式:bought
用法:buy + 东西 + for + 人
   = buy + 人 + 东西 为某人买……
例句:昨天Bobby为Tina买了一只狗。
   Bobby bought a dog for Tina yesterday.
   今晚我请大家吃饭。
   I am going to buy everyone dinner tonight.

pair n. 双,对(两个)
搭配:a pair of … 一双……
例句:这双鞋真好看。
   This pair of shoes is beautiful.

fashion n. 流行
搭配:fashion show 时装秀
   in fashion 流行
   out of fashion 不流行
例句:他的鞋子很流行。
   His shoes are in fashion.
   他的袜子很土。
   His socks are out of fashion.

uncomfortable a. 不舒服的
构成:un- 否定前缀:不……
   comfortable a. 舒服的
例句:我觉得不舒服。
   I feel uncomfortable.
   你令我感到不舒服。
   You make me uncomfortable.

wear v. 穿着(状态)
相关:put on v. 穿(动作)
   in + 颜色 穿……颜色衣服
例句:他戴着一定新帽子。
   He is wearing a new hat.
   他正在戴帽子。
   He is putting on a hat.
   穿红色衬衫的男孩是Bobby.
   The boy in red shirt is Bobby.

课文部分

在这里插入图片描述

语言点

Do you have any shoes like these?
你有像这样的鞋子吗?
any用于否定句和疑问句,some用于肯定句
like these:like“像”
例句:我想找到一个像你一样的人。
   I want to find someone like you.

What size? 什么尺寸?
完整形式:What size do you want?
口语一般用特殊疑问句代替全句
比如:How much? 多少钱?
   = How much is it?
   What? 发生了什么?
   = What happened?
   Why? 为什么是这样?
   = Why does it happen?

I’m afraid that I can’t.
恐怕我不能。
I’m afraid that + 句子 恐怕……
多用于否定情绪,并不是害怕而是用来表示。
例句:恐怕我不知道。
   I’m afraid that I don’t know.
   恐怕他不在。【打电话】
   I’m afraid he is not here.

They were is fashion last year …
去年他们很流行……
搭配:be in fashion 在流行
   be out of fashion 过时了
例句:You are so out. 你太土了!

They look very uncomfortable.
他们看起来非常不舒服。
look:看起来——感官动词
例句:它看起来很恶心。
   It looks awful.

请结合下面代码写出实现4的代码,4.模型评估与部署 在测试集上评估模型性能 计算准确率、准确率、响应率、F1分数等指标 模型部署与服务化import torch from torch.utils.data import DataLoader, Dataset from transformers import BertTokenizer, BertModel, AdamW, get_cosine_schedule_with_warmup import torch.nn as nn # 自定义数据集类 class HotelReviewDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length=128): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def __len__(self): return len(self.texts) def __getitem__(self, idx): text = self.texts[idx] label = self.labels[idx] encoding = self.tokenizer( text, add_special_tokens=True, max_length=self.max_length, padding='max_length', truncation=True, return_tensors='pt' ) return { 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'label': torch.tensor(label, dtype=torch.long) } # 定义分类模型 class SentimentClassifier(nn.Module): def __init__(self, bert_model_name='bert-base-uncased', num_classes=2): super(SentimentClassifier, self).__init__() self.bert = BertModel.from_pretrained(bert_model_name) self.classifier = nn.Linear(self.bert.config.hidden_size, num_classes) def forward(self, input_ids, attention_mask): outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask) cls_output = outputs.last_hidden_state[:, 0, :] logits = self.classifier(cls_output) return logits # 训练与验证函数 def train_model(model, train_loader, val_loader, device, epochs=5, lr=2e-5): optimizer = AdamW(model.parameters(), lr=lr, weight_decay=1e-4) scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=len(train_loader), num_training_steps=epochs * len(train_loader)) loss_fn = nn.CrossEntropyLoss() for epoch in range(epochs): model.train() total_loss = 0 for batch in train_loader: input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) optimizer.zero_grad() logits = model(input_ids, attention_mask) loss = loss_fn(logits, labels) loss.backward() optimizer.step() scheduler.step() total_loss += loss.item() # 验证阶段 model.eval() correct = 0 total = 0 with torch.no_grad(): for batch in val_loader: input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) logits = model(input_ids, attention_mask) predictions = torch.argmax(logits, dim=1) correct += (predictions == labels).sum().item() total += labels.size(0) accuracy = correct / total print(f"Epoch {epoch+1}/{epochs}, Loss: {total_loss/len(train_loader):.4f}, Val Accuracy: {accuracy:.4f}") # 示例调用 if __name__ == "__main__": # 假设已有训练集和验证集的文本和标签 train_texts = ["Great service and clean room", "The bed was uncomfortable", ...] # 示例训练文本 train_labels = [1, 0, ...] # 示例训练标签 val_texts = ["Nice location but noisy", "Excellent breakfast", ...] # 示例验证文本 val_labels = [0, 1, ...] # 示例验证标签 tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') train_dataset = HotelReviewDataset(train_texts, train_labels, tokenizer) val_dataset = HotelReviewDataset(val_texts, val_labels, tokenizer) train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=16) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = SentimentClassifier().to(device) train_model(model, train_loader, val_loader, device, epochs=5, lr=2e-5)
07-09
### 模型评估与部署实现 在BERT文本分类模型的训练完成后,需要对模型进行评估以衡量其性能,并将其部署为服务以便实际应用。以下代码实现了测试集上的评估指标(准确率、召回率、F1分数)计算,并提供基于Flask的轻量级模型服务化方案。 #### 模型评估部分 ```python from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score import torch def evaluate_model(model, data_loader, device): model.eval() predictions = [] true_labels = [] with torch.no_grad(): for batch in data_loader: input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) logits = model(input_ids, attention_mask) batch_preds = torch.argmax(logits, dim=1).cpu().numpy() predictions.extend(batch_preds) true_labels.extend(labels.cpu().numpy()) accuracy = accuracy_score(true_labels, predictions) precision = precision_score(true_labels, predictions, average='binary', pos_label=1) recall = recall_score(true_labels, predictions, average='binary', pos_label=1) f1 = f1_score(true_labels, predictions, average='binary', pos_label=1) return { 'accuracy': accuracy, 'precision': precision, 'recall': recall, 'f1_score': f1 } ``` 该函数用于在测试集或验证集上评估模型性能,计算了准确率、精确率、召回率和F1分数等关键指标[^2]。 #### 模型服务化部署方案 使用 Flask 构建一个简单的 REST API 服务,将 BERT 模型封装为可调用的 Web 服务: ```python from flask import Flask, request, jsonify import torch from transformers import BertTokenizer app = Flask(__name__) model = None tokenizer = None device = None def load_model(): global model, tokenizer, device model_path = "bert_sentiment_model.pth" model = SentimentClassifier(num_classes=2) model.load_state_dict(torch.load(model_path)) model.to(device) model.eval() tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') device = torch.device("cuda" if torch.cuda.is_available() else "cpu") @app.route('/predict', methods=['POST']) def predict(): data = request.json text = data.get('text', '') encoding = tokenizer(text, add_special_tokens=True, max_length=128, padding='max_length', truncation=True, return_tensors='pt') input_ids = encoding['input_ids'].to(device) attention_mask = encoding['attention_mask'].to(device) with torch.no_grad(): logits = model(input_ids, attention_mask) prediction = torch.argmax(logits, dim=1).cpu().numpy()[0] return jsonify({ 'sentiment': 'positive' if prediction == 1 else 'negative', 'confidence': torch.softmax(logits, dim=1).cpu().numpy().tolist()[0] }) if __name__ == '__main__': load_model() app.run(host='0.0.0.0', port=5000) ``` 上述代码构建了一个基于 Flask 的 RESTful 接口服务,接收 POST 请求并返回情感预测结果,适用于生产环境下的模型部署需求[^3]。 #### 性能优化建议 为了提升模型推理效率,可在服务端引入缓存机制以避免重复请求的冗余计算;同时,可以结合 ONNX 或 TorchScript 对模型进行序列化和加速,提高响应速度[^3]。此外,在多用户并发访问场景下,建议采用 Gunicorn + Nginx 部署方式,增强服务稳定性和吞吐能力。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值