深度学习-04-NLP项目实战

🚀 Day04 - NLP项目实战

📖 导读

第四天,进入项目实战阶段。


🏗️ 项目流程

1. 数据加载

python 复制代码
import pandas as pd

train_df = pd.read_csv('train.tsv', sep='\t')
test_df = pd.read_csv('test.tsv', sep='\t')

2. 数据清洗

python 复制代码
import re

def clean_text(text):
    text = re.sub(r'[^\w\s]', '', text)
    text = text.lower()
    return text

🔧 特征工程

3.1 文本特征

python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer(max_features=10000, ngram_range=(1, 2))
X_train = tfidf.fit_transform(train_df['text'])

3.2 长度特征

python 复制代码
train_df['length'] = train_df['text'].apply(len)
train_df['word_count'] = train_df['text'].apply(lambda x: len(x.split()))

🧠 模型构建

4.1 简单RNN

python 复制代码
class TextRNN(nn.Module):
    def __init__(self, vocab_size, embed_size, hidden_size):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.rnn = nn.GRU(embed_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, 1)
    
    def forward(self, x):
        embed = self.embedding(x)
        output, hidden = self.rnn(embed)
        return self.fc(hidden[-1])

4.2 Attention分类

python 复制代码
class AttentionClassifier(nn.Module):
    def __init__(self, vocab_size, embed_size, hidden_size):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True)
        self.attention = Attention(hidden_size * 2)
        self.fc = nn.Linear(hidden_size * 2, 1)
    
    def forward(self, x):
        embed = self.embedding(x)
        output, _ = self.lstm(embed)
        context, _ = self.attention(output)
        return self.fc(context)

🚀 训练与评估

5.1 训练循环

python 复制代码
for epoch in range(10):
    model.train()
    for batch in dataloader:
        optimizer.zero_grad()
        output = model(batch.x)
        loss = criterion(output, batch.y)
        loss.backward()
        optimizer.step()

5.2 评估

python 复制代码
from sklearn.metrics import classification_report

model.eval()
preds = model(test_x)
print(classification_report(test_y, preds))

📝 总结

Day04完成项目实战全流程。

相关推荐
倔强的石头10614 小时前
腾讯云Lighthouse一键部署OpenClaw,接入蓝耘MaaS打造微信知识库管家
notion·蓝耘·openclaw
惊鸿一博15 小时前
自动驾驶的 BEV 特征(Bird’s Eye View Feature)
人工智能·机器学习·自动驾驶
碳基硅坊16 小时前
Mac Studio M3 Ultra 运行大模型实测:Qwen3.6 vs 6款主流模型工具调用对比
人工智能·qwen·qwen3.6
TeDi TIVE1 天前
开源模型应用落地-工具使用篇-Spring AI-高阶用法(九)
人工智能·spring·开源
MY_TEUCK1 天前
Sealos 平台部署实战指南:结合 Cursor 与版本发布流程
java·人工智能·学习·aigc
三毛的二哥1 天前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
j_xxx404_1 天前
大语言模型 (LLM) 零基础入门:核心原理、训练机制与能力全解
人工智能·ai·transformer
飞哥数智坊1 天前
全新 SOLO 在日常办公中的实际体验
人工智能·solo
<-->1 天前
Megatron(全称 Megatron-LM,由 NVIDIA 开发)和 DeepSpeed(由 Microsoft 开发)
人工智能·pytorch·python·深度学习·transformer
朝新_1 天前
【Spring AI 】图像与语音模型实战
java·人工智能·spring