pytorch实践:名字分类的RNN模型

本文介绍了一个基于RNN的模型,通过处理不同国家的名字如Bob(英国)、bingbingWang(中国),设计了一个用于根据名字预测所属国家的算法。模型使用了PyTorch库,包含数据预处理、模型定义、训练和评估过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


前言

任务是这样的,我们需要设计一个模型,针对不同的名字,判断他到底是哪个国家。
比如:
bob 英国的
bingbing Wang 中国的

一、先上代码

#根据名字分类国家
import numpy as np
import torch
from torch.utils.data import DataLoader,Dataset
import matplotlib.pyplot as plt
import gzip
import csv
import time

class NameDataset(Dataset):
    def __init__(self,is_train_set=True):
        filename='names_train.csv.gz'if is_train_set else'names_test.csv.gz'
        #多种不同的方式读取数据,gzip格式如下
        with gzip.open(filename,'rt') as f:
            reader=csv.reader(f)
            rows=list(reader)#name,lauguage对
        self.names=[row[0] for row in rows]
        self.len=len(self.names)
        self.countries=[row[1] for row in rows]
        #set 集合,去除重复元素 sort排序 list变成列表
        self.country_list=list(sorted(set(self.countries)))
        #country变成一个字典
        self.country_dict=self.getCountryDict()

        self.country_num=len(self.country_list)#索引总数

    #save countries and its index in list and dictionary
    def __getitem__(self, index):
        #名字string country索引
        return self.names[index],self.country_dict[self.countries[index]]

    def __len__(self):
        return self.len

    #convert list to dictionary
    def getCountryDict(self):
        country_dict=dict()#空字典
        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值