深度学习-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完成项目实战全流程。

相关推荐
AAA修煤气灶刘哥6 小时前
权重已经读进缓存了,7B 模型怎么还要等 43 秒?
人工智能·性能优化·阿里巴巴
oil欧哟6 小时前
AI Agent 的高效上下文工程:核心原理与实战拆解
人工智能
邂逅and回眸7 小时前
机器人的软件栈:ROS 2、实时中间件与数据流
人工智能·中间件·机器人
AAA修煤气灶刘哥7 小时前
AI 写的 SQL 跑通了,为什么和财务报表对不上?
人工智能·后端·算法
程序员cxuan8 小时前
这 6 个 Gemini 命令,真给我用爽了
人工智能·后端·程序员
狂师8 小时前
别只会用 Playwright、Appium了?这 8 款开源 AI 自动化工具实测推荐!
人工智能·开源·测试
东坡肘子8 小时前
我的代码我做主 -- 肘子的 Swift 周报 #164
人工智能·swiftui·swift
sharemylove17 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
yyzc1111117 小时前
当中小微实体店面临经营困境时如何借助顺成汇创旗下荟生意品牌实现数字化智慧营销
大数据·运维·人工智能
Csvn20 小时前
输出脱敏了,trace 里全是明文——用户数据的四个落点都得堵(S04)
人工智能·aigc·agent