【Pytorch】RNN for Name Classification

在这里插入图片描述

参考学习来自:

  • https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
  • RNN完成姓名分类
  • https://download.pytorch.org/tutorial/data.zip

导入库

import glob # 用于查找符合规则的文件名
import os
import unicodedata
import string
import torch
import torch.nn as nn
import torch.optim as optim
import random

GPU 配置

"Device configuration"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

导入数据

在这里插入图片描述

"导入数据"
def findFiles(path):return glob.glob(path)for i in findFiles('./data/names/*.txt'):print(i)

output

./data/names/Korean.txt
./data/names/Irish.txt
./data/names/Portuguese.txt
./data/names/Vietnamese.txt
./data/names/Czech.txt
./data/names/Russian.txt
./data/names/Scottish.txt
./data/names/German.txt
./data/names/Polish.txt
./data/names/Spanish.txt
./data/names/English.txt
./data/names/French.txt
./data/names/Japanese.txt
./data/names/Dutch.txt
./data/names/Greek.txt
./data/names/Chinese.txt
./data/names/Italian.txt
./data/names/Arabic.txt

查看名字所有字符

all_letters = string.ascii_letters + " .,;'" #所有的字母和标点
print(all_letters)  # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,;'n_letters = len(all_letters)
print(n_letters)  # 57

字符都转化为 ASCII 形式

# Turn a Unicode string to plain ASCII
# Thanks to https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):return ''.join(c for c in unicodedata.normalize('NFD', s)if unicodedata.category(c) != 'Mn'and c in all_letters)
print(unicodeToAscii('Ślusàrski'))  # Slusarskicategory_lines = {}  # 每个语言下的名字
all_categories = []  # 保存所有的语言的名字# 读文件, 返回文件中的每一个
def readLines(filename):# 读文件, 去空格, 按换行进行划分lines = open(filename, encoding='utf-8').read().strip().split('\n')return [unicodeToAscii(line) for line in lines]# 顺序读取每一个文件, 保存其中的姓名
for filename in findFiles('./data/names/*.txt'):# basename返回基础的文件名# splitext将文件名和后缀分开category = os.path.splitext(os.path.basename(filename))[0]all_categories.append(category)lines = readLines(filename)category_lines[category] = linesn_categories = len(all_categories)
# 一共有18种语言的名字
print(len(category_lines))  # 18# 查看某种语言的名字
print(category_lines.keys())
"""
dict_keys(['Korean', 'Irish', 'Portuguese', 'Vietnamese', 'Czech', 'Russian', 'Scottish', 'German', 'Polish', 
'Spanish', 'English', 'French', 'Japanese', 'Dutch', 'Greek', 'Chinese', 'Italian', 'Arabic'])
"""
print(category_lines['English'][:5])  # ['Abbas', 'Abbey', 'Abbott', 'Abdi', 'Abel']

名字转化为 Tensor

"将Name转为Tensor"
# Find letter index from all_letters, e.g. "a"=0
def letterToIndex(letter):# 返回字母在字母表中的位置# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,;'return all_letters.find(letter)# 将整个名字转为<line_length x 1 x n_letters>
def lineToTensor(line):tensor = torch.zeros(len(line), 1, n_letters)for li, letter in enumerate(line):tensor[li][0][letterToIndex(letter)] = 1return tensorprint(lineToTensor('Bryant').shape)  # torch.Size([6, 1, 57])
print(lineToTensor('Mike').shape)  # torch.Size([4, 1, 57])
print(lineToTensor('Mike'))

output

tensor([[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]]])

定义 RNN 分类网络

"定义网络"
class RNN_NAME(nn.Module):def __init__(self, input_size, hidden_size, output_size, layers, batch_size):super(RNN_NAME, self).__init__()# 这里的input_size相当于是特征的个数, 这里即是所有字母的个数57self.input_size = input_size# 这里相当于是rnn输出的维数self.hidden_size = hidden_size# 这里是分类的个数, 这里相当于是18, 一共有18类self.output_size = output_size# 这里是rnn的层数self.layers = layers# batchsize的个数self.batch_size = batch_sizeself.gru = nn.GRU(input_size = self.input_size, hidden_size = self.hidden_size, num_layers = self.layers)self.FC = nn.Linear(self.hidden_size, self.output_size)def init_hidden(self):return torch.zeros(self.layers, self.batch_size, self.hidden_size).to(device)def forward(self, x):self.batch_size = x.size(1)self.hidden = self.init_hidden() # 初始化memory的内容rnn_out, self.hidden = self.gru(x,self.hidden)out = self.FC(rnn_out[-1])return out

RNN 网络初始化

"初始化"
layers = 3
input_size = n_letters
hidden_size = 128
output_size = len(all_categories) # 18类
batch_size = 1  # 因为这里name的长度不相同, 所以将batch_size设为1
# 网络初始化
rnn_name = RNN_NAME(input_size, hidden_size, output_size, layers, batch_size).to(device)
# 测试网络输入输出
input_data = lineToTensor('Mike')
out_data = rnn_name(input_data.to(device))
print(out_data.size())
# torch.Size([1, 18])
print(out_data)
"""
tensor([[ 0.0051, -0.0081, -0.0906,  0.1054,  0.0679, -0.0187, -0.0497, -0.0349,-0.0466,  0.0004, -0.0099, -0.0940, -0.0201, -0.0694, -0.0542, -0.0807,0.0005,  0.1373]], grad_fn=<AddmmBackward0>)
"""

准备训练数据集

"准备训练数据"
# 打印最后显示的结果def categoryFromOutput(output):top_n, top_i = output.topk(1)category_i = top_i[0].item()return all_categories[category_i], category_i# Get a random training example
def randomChoice(l):# 随机返回一个l中的分类return l[random.randint(0, len(l)-1)]def randomTrainingExample():"""随机挑选一种语言的一个名字, 用来产生训练需要的数据"""category = randomChoice(all_categories)  # 随机选一个语言line = randomChoice(category_lines[category])  # 随机从这个语言里选一个名字category_tensor = torch.tensor([all_categories.index(category)]).long() # 将分类转为Tensorline_tensor = lineToTensor(line)  # 将名字转为Tensorreturn category, line, category_tensor, line_tensorfor i in range(10):category, line, category_tensor, line_tensor = randomTrainingExample()print('category = ', category, '/ line = ', line)
"""
category =  Scottish / line =  Miller
category =  Irish / line =  O'Mooney
category =  Dutch / line =  Kools
category =  French / line =  Bouchard
category =  French / line =  Masson
category =  English / line =  May
category =  Spanish / line =  Holguin
category =  Portuguese / line =  Moreno
category =  Greek / line =  Nomikos
category =  Czech / line =  Cernohous
"""

计算预测精度

"计算精度"
def get_accuracy(logit, target):corrects = (torch.max(logit, 1)[1].view(target.size()).data == target.data).sum()accuracy = 100.0 * corrects/batch_sizereturn accuracy.item()

网络训练

"训练"criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(rnn_name.parameters(),lr=0.005)
N_EPHOCS = 100
# 共有20074个数据
n_iters = 2000  # 训练n_iters个名字
print_every = 200  # 每print_every轮打印一次结果, 并传递一次误差, 更新系数
for epoch in range(N_EPHOCS):train_running_loss = 0.0loss = torch.tensor([0.0]).float().to(device)train_count = 0rnn_name.train()# trainging roundfor iter in range(1, n_iters+1):# 获取样本category, line, category_tensor, line_tensor = randomTrainingExample()category_tensor = category_tensor.to(device)line_tensor = line_tensor.to(device)# 进行训练optimizer.zero_grad()# reset hidden statesrnn_name.hidden = rnn_name.init_hidden()# forward+backward+optimizeoutputs = rnn_name(line_tensor)guess, guess_i = categoryFromOutput(outputs)if guess == category:train_count = train_count + 1# print(iter)loss = loss + criterion(outputs, category_tensor)if iter % print_every == 0:correct = '✓' if guess == category else '✗ ({})'.format(category)print('{} /{} {}'.format(line, guess, correct))# 进行反向传播(print_every次传一次误差)loss.backward()optimizer.step()train_running_loss = train_running_loss + loss.detach().item()loss = torch.tensor([0.0]).float().to(device)# 查看准确率train_acc = train_count / n_iters * 100print('=======')print('Epoch : {:0>2d} | Loss : {:<6.4f} | Train Accuracy : {:<6.2f}%'.format(epoch, train_running_loss/n_iters, train_acc))print('=======')"验证"
test_count = 0
test_num = 500 # 测试500个名字
rnn_name.eval()
for test_iter in range(1, test_num+1):category, line, category_tensor, line_tensor = randomTrainingExample()outputs = rnn_name(line_tensor.to(device))guess, guess_i = categoryFromOutput(outputs)if guess == category:test_count = test_count + 1
print('Test Accuracy : {:<6.4f}%'.format(test_count/test_num*100))
"""
=======
Epoch : 71 | Loss : 0.2698 | Train Accuracy : 92.35 %
=======
Konda /Japanese ✓
Seighin /Irish ✓
Sedmik /Czech ✓
Jestkov /Russian ✓
So /Korean ✓
Laar /Dutch ✓
Mazza /Italian ✓
Abl /Czech ✓
Doyle /Irish ✓
Skwor /Czech ✓
=======
Epoch : 72 | Loss : 0.2583 | Train Accuracy : 91.40 %
=======
Martoyas /Greek ✗ (Russian)
Hallett /English ✓
Bermudez /Spanish ✓
Bonhomme /French ✓
Lam /Chinese ✗ (Vietnamese)
Kourempes /Greek ✓
Matsuki /Japanese ✓
Sokolofsky /Polish ✓
Kuipers /Dutch ✓
Aller /Dutch ✓
=======
Epoch : 73 | Loss : 0.2564 | Train Accuracy : 91.65 %
=======
Xiao /Chinese ✓
Lian /Chinese ✓
Prill /Czech ✓
Glatter /Czech ✓
Bureau /French ✓
Vallance /French ✗ (English)
Johnstone /Scottish ✓
Kassab /Arabic ✓
Atiyeh /Arabic ✓
Luong /Vietnamese ✓
=======
Epoch : 74 | Loss : 0.2610 | Train Accuracy : 91.60 %
=======
Poirier /French ✓
Hahn /German ✓
Botros /Arabic ✓
Adrichem /Dutch ✓
Rios /Portuguese ✗ (Spanish)
Zangari /Italian ✓
Mccallum /Scottish ✓
Ferro /Portuguese ✓
Kim /Vietnamese ✗ (Korean)
Chang /Korean ✓
=======
Epoch : 75 | Loss : 0.2792 | Train Accuracy : 90.85 %
=======
Monte /Italian ✓
Han /Vietnamese ✗ (Korean)
Ying /Chinese ✓
O'Driscoll /Irish ✓
Poirier /French ✓
Tsuruya /Japanese ✓
Ralph /Czech ✗ (English)
Bonheur /French ✓
Romagna /Italian ✓
Krakowski /Polish ✓
=======
Epoch : 76 | Loss : 0.3000 | Train Accuracy : 90.85 %
=======
Fay /French ✓
Plisek /Czech ✓
Travere /French ✓
Moon /Korean ✓
Aalst /Dutch ✓
Sassa /Japanese ✓
Holzmann /German ✓
Kruessel /Czech ✓
Truong /Vietnamese ✓
Kassab /Arabic ✓
=======
Epoch : 77 | Loss : 0.2602 | Train Accuracy : 92.00 %
=======
Janda /Polish ✓
Doan /Vietnamese ✓
O'Reilly /Irish ✓
Torres /Portuguese ✓
Esipovich /Russian ✓
Johnston /Scottish ✓
Viteri /Spanish ✗ (Italian)
Vandroogenbroeck /Dutch ✓
Montero /Spanish ✓
Wan /Chinese ✓
=======
Epoch : 78 | Loss : 0.2460 | Train Accuracy : 92.35 %
=======
Ha /Korean ✗ (Vietnamese)
Christie /Scottish ✓
Pereira /Portuguese ✓
Kuiper /Dutch ✓
Bautista /Spanish ✓
Takewaki /Japanese ✓
Ying /Chinese ✓
Sokoloff /Polish ✓
Raghailligh /Irish ✓
Edgell /English ✓
=======
Epoch : 79 | Loss : 0.2640 | Train Accuracy : 91.60 %
=======
Neal /English ✓
Kafka /Czech ✓
Hay /Scottish ✓
Pelletier /French ✓
Wilchek /Czech ✓
Marchesi /Italian ✓
Michel /Spanish ✓
Ling /Chinese ✓
Zou /Chinese ✓
Freitas /Portuguese ✓
=======
Epoch : 80 | Loss : 0.2579 | Train Accuracy : 92.60 %
=======
Kelly /Scottish ✓
Chou /Korean ✓
Unsworth /English ✓
Larue /French ✓
Tron /Vietnamese ✓
Herodes /Czech ✓
Fremut /Czech ✓
Thai /Vietnamese ✓
Clark /Irish ✗ (Scottish)
Halenkov /Russian ✓
=======
Epoch : 81 | Loss : 0.2453 | Train Accuracy : 92.40 %
=======
Than /Vietnamese ✓
Pfeifer /Czech ✓
Kennedy /Scottish ✓
Klerkx /Dutch ✓
Freitas /Portuguese ✓
Miller /Scottish ✓
Deeb /Arabic ✓
Almetov /Russian ✓
Li /Korean ✓
Perez /Spanish ✓
=======
Epoch : 82 | Loss : 0.2579 | Train Accuracy : 91.85 %
=======
Horiatis /Greek ✓
Clowes /English ✓
Santos /Portuguese ✓
Mochan /Irish ✓
Sokolof /Polish ✓
Ogterop /Dutch ✓
Schwartz /Czech ✓
Abadi /Arabic ✓
Winogrodzki /Polish ✓
Bazzhin /Russian ✓
=======
Epoch : 83 | Loss : 0.2397 | Train Accuracy : 92.25 %
=======
Ybarra /Spanish ✓
Jacobson /English ✓
Shi /Chinese ✓
Berg /Dutch ✓
Araya /Spanish ✓
Banos /Greek ✓
Winograd /Polish ✓
Schneider /German ✗ (Czech)
Calligaris /Italian ✓
Hasbulatov /Russian ✓
=======
Epoch : 84 | Loss : 0.2466 | Train Accuracy : 92.25 %
=======
Felkerzam /Polish ✗ (Russian)
Gomolka /Polish ✓
Belo /Portuguese ✓
Santos /Portuguese ✓
Rim /Korean ✓
Solomon /French ✓
Agnellutti /Italian ✓
Santana /Portuguese ✓
Ramaker /Dutch ✓
Palmisano /Italian ✓
=======
Epoch : 85 | Loss : 0.2390 | Train Accuracy : 92.80 %
=======
Moraitopoulos /Greek ✓
Rosenberger /German ✓
Torres /Portuguese ✓
Sabbagh /Arabic ✓
Aggelen /Dutch ✓
Chieu /Chinese ✓
Ukhtomsky /Russian ✓
Kouros /Greek ✓
Portyansky /Russian ✓
Dinh /Vietnamese ✓
=======
Epoch : 86 | Loss : 0.2173 | Train Accuracy : 93.15 %
=======
Jaskulski /Polish ✓
Mendez /Spanish ✓
Smyth /English ✓
Mo /Korean ✓
Seegers /Dutch ✓
Elford /English ✓
Lau /Chinese ✓
Sargent /French ✓
Zeman /Czech ✓
Ohme /German ✓
=======
Epoch : 87 | Loss : 0.2189 | Train Accuracy : 93.00 %
=======
Gwang  /Korean ✓
Zhernakov /Russian ✓
Quraishi /Arabic ✓
Asker /Arabic ✓
Franco /Portuguese ✓
Bacon /Czech ✓
Weineltk /Czech ✓
Thuy /Vietnamese ✓
Close /Greek ✓
Xiang /Chinese ✓
=======
Epoch : 88 | Loss : 0.2497 | Train Accuracy : 91.95 %
=======
Basara /Arabic ✓
Esteves /Portuguese ✓
Metz /German ✓
Lopez /Spanish ✓
Bukoski /Polish ✓
Rao /Italian ✓
Klerk /Dutch ✓
Espinoza /Spanish ✓
Wehunt /German ✓
Giehl /German ✓
=======
Epoch : 89 | Loss : 0.2454 | Train Accuracy : 92.70 %
=======
Deniau /French ✓
Bover /Spanish ✗ (Italian)
Soho /Japanese ✓
Ron /Korean ✓
Dolezal /Czech ✓
Yamamura /Japanese ✓
Ramsay /Scottish ✓
Fromm /German ✓
Huerta /Spanish ✓
Colman /Irish ✓
=======
Epoch : 90 | Loss : 0.2432 | Train Accuracy : 92.55 %
=======
Fei /Chinese ✓
Dinh /Vietnamese ✓
Krawiec /Czech ✓
Urbanek /Czech ✓
Yan /Chinese ✓
Giehl /German ✓
Riain /Irish ✓
Zhestkov /Russian ✓
Almetiev /Russian ✓
Deniel /French ✓
=======
Epoch : 91 | Loss : 0.2318 | Train Accuracy : 92.45 %
=======
Macleod /Scottish ✓
Savatier /French ✓
Chong /Chinese ✗ (Korean)
Prchal /Czech ✓
Tsoumada /Greek ✓
Agosti /Italian ✓
Mojjis /Czech ✓
Mitsui /Japanese ✓
San nicolas /Spanish ✓
Kokoris /Greek ✓
=======
Epoch : 92 | Loss : 0.2163 | Train Accuracy : 92.25 %
=======
Marubeni /Japanese ✓
Suh /Korean ✓
Klerks /Dutch ✓
Roma /Spanish ✓
Lac /Vietnamese ✓
Khoury /Arabic ✓
Hoefler /German ✓
Gibson /Scottish ✓
Jasso /Spanish ✓
Oirschotten /Dutch ✓
=======
Epoch : 93 | Loss : 0.2329 | Train Accuracy : 92.90 %
=======
Kikuchi /Japanese ✓
Blecher /German ✓
Ying /Chinese ✓
Nahas /Arabic ✓
Araujo /Portuguese ✓
Koemans /Dutch ✓
Durant /French ✓
Martzenyuk /Russian ✓
Petru /Czech ✓
Wood /Scottish ✓
=======
Epoch : 94 | Loss : 0.2080 | Train Accuracy : 93.35 %
=======
Vespa /Italian ✓
Kowalczyk /Polish ✓
Nahas /Arabic ✓
Tresler /German ✓
Caivano /Italian ✓
Pho /Vietnamese ✓
Dael /Dutch ✓
Heidl /Czech ✓
Totolos /Greek ✓
Adlersflugel /German ✓
=======
Epoch : 95 | Loss : 0.2400 | Train Accuracy : 92.45 %
=======
Zwolenksy /Czech ✓
Chermak /Czech ✓
Sgro /Italian ✓
Lestrange /French ✓
Hwang /Korean ✓
Barros /Spanish ✗ (Portuguese)
Boyle /Scottish ✓
Schmeling /German ✓
Poplawski /Polish ✓
Pantelas /Greek ✓
=======
Epoch : 96 | Loss : 0.2150 | Train Accuracy : 93.10 %
=======
Asher /English ✓
Sai /Vietnamese ✓
Hakimi /Arabic ✓
Sheng /Chinese ✓
Lebedevich /Russian ✓
Castellano /Spanish ✓
Battaglia /Italian ✓
Cardozo /Portuguese ✓
Sinagra /Italian ✓
Bumgarner /German ✓
=======
Epoch : 97 | Loss : 0.2359 | Train Accuracy : 92.80 %
=======
Lyes /English ✓
Do /Vietnamese ✓
Busch /German ✓
Shimura /Japanese ✓
O'Connor /Irish ✓
Geiger /German ✓
Reier /German ✓
Paris /French ✓
Sokolof /Polish ✓
Limarev /Russian ✓
=======
Epoch : 98 | Loss : 0.2369 | Train Accuracy : 92.55 %
=======
Osladil /Czech ✓
Roy /French ✓
Ortega /Spanish ✓
Ruzzier /Italian ✓
Chou /Korean ✓
Mateus /Portuguese ✓
Ibanez /Spanish ✓
Cabello /Spanish ✓
Duguay /French ✓
Yi /Korean ✓
=======
Epoch : 99 | Loss : 0.2192 | Train Accuracy : 92.65 %
=======
Test Accuracy : 94.8000%
"""

精度不足 95%

下面写写测试流程

"单独测试"
input_data = lineToTensor('WMN').to(device)
out_data = rnn_name(input_data)
print(out_data)
print(categoryFromOutput(out_data))
"""
tensor([[ 5.7034,  1.0659, -8.1210,  0.5218, -2.5818,  0.1362,  7.4420,  3.9547,1.0824, -7.2981,  4.0036, -2.2944,  1.6835, -3.5377, -7.6178,  9.8920,-0.5789, -1.0545]], device='cuda:0', grad_fn=<AddmmBackward0>)
('Chinese', 15)
"""input_data = lineToTensor('Huang').to(device)
out_data = rnn_name(input_data)
print(out_data)
print(categoryFromOutput(out_data))
"""
tensor([[ 4.1755, -1.2160, -3.8454,  5.4587, -4.6412,  0.8137,  1.2896,  1.7429,-1.3145, -2.1634,  1.0224, -2.7052,  2.1592,  1.1909, -8.0874, 10.2988,-1.9252, -0.0729]], device='cuda:0', grad_fn=<AddmmBackward0>)
('Chinese', 15)
"""

完整代码

import glob # 用于查找符合规则的文件名
import os
import unicodedata
import string
import torch
import torch.nn as nn
import torch.optim as optim
import random"Device configuration"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")"导入数据"
def findFiles(path):return glob.glob(path)for i in findFiles('./data/names/*.txt'):print(i)"""
./data/names/Korean.txt
./data/names/Irish.txt
./data/names/Portuguese.txt
./data/names/Vietnamese.txt
./data/names/Czech.txt
./data/names/Russian.txt
./data/names/Scottish.txt
./data/names/German.txt
./data/names/Polish.txt
./data/names/Spanish.txt
./data/names/English.txt
./data/names/French.txt
./data/names/Japanese.txt
./data/names/Dutch.txt
./data/names/Greek.txt
./data/names/Chinese.txt
./data/names/Italian.txt
./data/names/Arabic.txt
"""all_letters = string.ascii_letters + " .,;'" #所有的字母和标点
print(all_letters)  # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,;'n_letters = len(all_letters)
print(n_letters)  # 57# Turn a Unicode string to plain ASCII
# Thanks to https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):return ''.join(c for c in unicodedata.normalize('NFD', s)if unicodedata.category(c) != 'Mn'and c in all_letters)
print(unicodeToAscii('Ślusàrski'))  # Slusarskicategory_lines = {}  # 每个语言下的名字
all_categories = []  # 保存所有的语言的名字# 读文件, 返回文件中的每一个
def readLines(filename):# 读文件, 去空格, 按换行进行划分lines = open(filename, encoding='utf-8').read().strip().split('\n')return [unicodeToAscii(line) for line in lines]# 顺序读取每一个文件, 保存其中的姓名
for filename in findFiles('./data/names/*.txt'):# basename返回基础的文件名# splitext将文件名和后缀分开category = os.path.splitext(os.path.basename(filename))[0]all_categories.append(category)lines = readLines(filename)category_lines[category] = linesn_categories = len(all_categories)
# 一共有18种语言的名字
print(len(category_lines))  # 18# 查看某种语言的名字
print(category_lines.keys())
"""
dict_keys(['Korean', 'Irish', 'Portuguese', 'Vietnamese', 'Czech', 'Russian', 'Scottish', 'German', 'Polish', 
'Spanish', 'English', 'French', 'Japanese', 'Dutch', 'Greek', 'Chinese', 'Italian', 'Arabic'])
"""
print(category_lines['English'][:5])  # ['Abbas', 'Abbey', 'Abbott', 'Abdi', 'Abel']"将Name转为Tensor"
# Find letter index from all_letters, e.g. "a"=0
def letterToIndex(letter):# 返回字母在字母表中的位置# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,;'return all_letters.find(letter)# 将整个名字转为<line_length x 1 x n_letters>
def lineToTensor(line):tensor = torch.zeros(len(line), 1, n_letters)for li, letter in enumerate(line):tensor[li][0][letterToIndex(letter)] = 1return tensorprint(lineToTensor('Bryant').shape)  # torch.Size([6, 1, 57])
print(lineToTensor('Mike').shape)  # torch.Size([4, 1, 57])
print(lineToTensor('Mike'))"""
tensor([[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]],[[0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.]]])
""""定义网络"
class RNN_NAME(nn.Module):def __init__(self, input_size, hidden_size, output_size, layers, batch_size):super(RNN_NAME, self).__init__()# 这里的input_size相当于是特征的个数, 这里即是所有字母的个数57self.input_size = input_size# 这里相当于是rnn输出的维数self.hidden_size = hidden_size# 这里是分类的个数, 这里相当于是18, 一共有18类self.output_size = output_size# 这里是rnn的层数self.layers = layers# batchsize的个数self.batch_size = batch_sizeself.gru = nn.GRU(input_size = self.input_size, hidden_size = self.hidden_size, num_layers = self.layers)self.FC = nn.Linear(self.hidden_size, self.output_size)def init_hidden(self):return torch.zeros(self.layers, self.batch_size, self.hidden_size).to(device)def forward(self, x):self.batch_size = x.size(1)self.hidden = self.init_hidden() # 初始化memory的内容rnn_out, self.hidden = self.gru(x,self.hidden)out = self.FC(rnn_out[-1])return out"初始化"
layers = 3
input_size = n_letters
hidden_size = 128
output_size = len(all_categories) # 18类
batch_size = 1  # 因为这里name的长度不相同, 所以将batch_size设为1
# 网络初始化
rnn_name = RNN_NAME(input_size, hidden_size, output_size, layers, batch_size).to(device)
# 测试网络输入输出
input_data = lineToTensor('Mike')
out_data = rnn_name(input_data.to(device))
print(out_data.size())
# torch.Size([1, 18])
print(out_data)
"""
tensor([[ 0.0051, -0.0081, -0.0906,  0.1054,  0.0679, -0.0187, -0.0497, -0.0349,-0.0466,  0.0004, -0.0099, -0.0940, -0.0201, -0.0694, -0.0542, -0.0807,0.0005,  0.1373]], grad_fn=<AddmmBackward0>)
""""准备训练数据"
# 打印最后显示的结果def categoryFromOutput(output):top_n, top_i = output.topk(1)category_i = top_i[0].item()return all_categories[category_i], category_i# Get a random training example
def randomChoice(l):# 随机返回一个l中的分类return l[random.randint(0, len(l)-1)]def randomTrainingExample():"""随机挑选一种语言的一个名字, 用来产生训练需要的数据"""category = randomChoice(all_categories)  # 随机选一个语言line = randomChoice(category_lines[category])  # 随机从这个语言里选一个名字category_tensor = torch.tensor([all_categories.index(category)]).long() # 将分类转为Tensorline_tensor = lineToTensor(line)  # 将名字转为Tensorreturn category, line, category_tensor, line_tensorfor i in range(10):category, line, category_tensor, line_tensor = randomTrainingExample()print('category = ', category, '/ line = ', line)
"""
category =  Scottish / line =  Miller
category =  Irish / line =  O'Mooney
category =  Dutch / line =  Kools
category =  French / line =  Bouchard
category =  French / line =  Masson
category =  English / line =  May
category =  Spanish / line =  Holguin
category =  Portuguese / line =  Moreno
category =  Greek / line =  Nomikos
category =  Czech / line =  Cernohous
""""计算精度"
def get_accuracy(logit, target):corrects = (torch.max(logit, 1)[1].view(target.size()).data == target.data).sum()accuracy = 100.0 * corrects/batch_sizereturn accuracy.item()"训练"criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(rnn_name.parameters(),lr=0.005)
N_EPHOCS = 100
# 共有20074个数据
n_iters = 2000  # 训练n_iters个名字
print_every = 200  # 每print_every轮打印一次结果, 并传递一次误差, 更新系数
for epoch in range(N_EPHOCS):train_running_loss = 0.0loss = torch.tensor([0.0]).float().to(device)train_count = 0rnn_name.train()# trainging roundfor iter in range(1, n_iters+1):# 获取样本category, line, category_tensor, line_tensor = randomTrainingExample()category_tensor = category_tensor.to(device)line_tensor = line_tensor.to(device)# 进行训练optimizer.zero_grad()# reset hidden statesrnn_name.hidden = rnn_name.init_hidden()# forward+backward+optimizeoutputs = rnn_name(line_tensor)guess, guess_i = categoryFromOutput(outputs)if guess == category:train_count = train_count + 1# print(iter)loss = loss + criterion(outputs, category_tensor)if iter % print_every == 0:correct = '✓' if guess == category else '✗ ({})'.format(category)print('{} /{} {}'.format(line, guess, correct))# 进行反向传播(print_every次传一次误差)loss.backward()optimizer.step()train_running_loss = train_running_loss + loss.detach().item()loss = torch.tensor([0.0]).float().to(device)# 查看准确率train_acc = train_count / n_iters * 100print('=======')print('Epoch : {:0>2d} | Loss : {:<6.4f} | Train Accuracy : {:<6.2f}%'.format(epoch, train_running_loss/n_iters, train_acc))print('=======')"验证"
test_count = 0
test_num = 500 # 测试500个名字
rnn_name.eval()
for test_iter in range(1, test_num+1):category, line, category_tensor, line_tensor = randomTrainingExample()outputs = rnn_name(line_tensor.to(device))guess, guess_i = categoryFromOutput(outputs)if guess == category:test_count = test_count + 1
print('Test Accuracy : {:<6.4f}%'.format(test_count/test_num*100))
"""
=======
Epoch : 71 | Loss : 0.2698 | Train Accuracy : 92.35 %
=======
Konda /Japanese ✓
Seighin /Irish ✓
Sedmik /Czech ✓
Jestkov /Russian ✓
So /Korean ✓
Laar /Dutch ✓
Mazza /Italian ✓
Abl /Czech ✓
Doyle /Irish ✓
Skwor /Czech ✓
=======
Epoch : 72 | Loss : 0.2583 | Train Accuracy : 91.40 %
=======
Martoyas /Greek ✗ (Russian)
Hallett /English ✓
Bermudez /Spanish ✓
Bonhomme /French ✓
Lam /Chinese ✗ (Vietnamese)
Kourempes /Greek ✓
Matsuki /Japanese ✓
Sokolofsky /Polish ✓
Kuipers /Dutch ✓
Aller /Dutch ✓
=======
Epoch : 73 | Loss : 0.2564 | Train Accuracy : 91.65 %
=======
Xiao /Chinese ✓
Lian /Chinese ✓
Prill /Czech ✓
Glatter /Czech ✓
Bureau /French ✓
Vallance /French ✗ (English)
Johnstone /Scottish ✓
Kassab /Arabic ✓
Atiyeh /Arabic ✓
Luong /Vietnamese ✓
=======
Epoch : 74 | Loss : 0.2610 | Train Accuracy : 91.60 %
=======
Poirier /French ✓
Hahn /German ✓
Botros /Arabic ✓
Adrichem /Dutch ✓
Rios /Portuguese ✗ (Spanish)
Zangari /Italian ✓
Mccallum /Scottish ✓
Ferro /Portuguese ✓
Kim /Vietnamese ✗ (Korean)
Chang /Korean ✓
=======
Epoch : 75 | Loss : 0.2792 | Train Accuracy : 90.85 %
=======
Monte /Italian ✓
Han /Vietnamese ✗ (Korean)
Ying /Chinese ✓
O'Driscoll /Irish ✓
Poirier /French ✓
Tsuruya /Japanese ✓
Ralph /Czech ✗ (English)
Bonheur /French ✓
Romagna /Italian ✓
Krakowski /Polish ✓
=======
Epoch : 76 | Loss : 0.3000 | Train Accuracy : 90.85 %
=======
Fay /French ✓
Plisek /Czech ✓
Travere /French ✓
Moon /Korean ✓
Aalst /Dutch ✓
Sassa /Japanese ✓
Holzmann /German ✓
Kruessel /Czech ✓
Truong /Vietnamese ✓
Kassab /Arabic ✓
=======
Epoch : 77 | Loss : 0.2602 | Train Accuracy : 92.00 %
=======
Janda /Polish ✓
Doan /Vietnamese ✓
O'Reilly /Irish ✓
Torres /Portuguese ✓
Esipovich /Russian ✓
Johnston /Scottish ✓
Viteri /Spanish ✗ (Italian)
Vandroogenbroeck /Dutch ✓
Montero /Spanish ✓
Wan /Chinese ✓
=======
Epoch : 78 | Loss : 0.2460 | Train Accuracy : 92.35 %
=======
Ha /Korean ✗ (Vietnamese)
Christie /Scottish ✓
Pereira /Portuguese ✓
Kuiper /Dutch ✓
Bautista /Spanish ✓
Takewaki /Japanese ✓
Ying /Chinese ✓
Sokoloff /Polish ✓
Raghailligh /Irish ✓
Edgell /English ✓
=======
Epoch : 79 | Loss : 0.2640 | Train Accuracy : 91.60 %
=======
Neal /English ✓
Kafka /Czech ✓
Hay /Scottish ✓
Pelletier /French ✓
Wilchek /Czech ✓
Marchesi /Italian ✓
Michel /Spanish ✓
Ling /Chinese ✓
Zou /Chinese ✓
Freitas /Portuguese ✓
=======
Epoch : 80 | Loss : 0.2579 | Train Accuracy : 92.60 %
=======
Kelly /Scottish ✓
Chou /Korean ✓
Unsworth /English ✓
Larue /French ✓
Tron /Vietnamese ✓
Herodes /Czech ✓
Fremut /Czech ✓
Thai /Vietnamese ✓
Clark /Irish ✗ (Scottish)
Halenkov /Russian ✓
=======
Epoch : 81 | Loss : 0.2453 | Train Accuracy : 92.40 %
=======
Than /Vietnamese ✓
Pfeifer /Czech ✓
Kennedy /Scottish ✓
Klerkx /Dutch ✓
Freitas /Portuguese ✓
Miller /Scottish ✓
Deeb /Arabic ✓
Almetov /Russian ✓
Li /Korean ✓
Perez /Spanish ✓
=======
Epoch : 82 | Loss : 0.2579 | Train Accuracy : 91.85 %
=======
Horiatis /Greek ✓
Clowes /English ✓
Santos /Portuguese ✓
Mochan /Irish ✓
Sokolof /Polish ✓
Ogterop /Dutch ✓
Schwartz /Czech ✓
Abadi /Arabic ✓
Winogrodzki /Polish ✓
Bazzhin /Russian ✓
=======
Epoch : 83 | Loss : 0.2397 | Train Accuracy : 92.25 %
=======
Ybarra /Spanish ✓
Jacobson /English ✓
Shi /Chinese ✓
Berg /Dutch ✓
Araya /Spanish ✓
Banos /Greek ✓
Winograd /Polish ✓
Schneider /German ✗ (Czech)
Calligaris /Italian ✓
Hasbulatov /Russian ✓
=======
Epoch : 84 | Loss : 0.2466 | Train Accuracy : 92.25 %
=======
Felkerzam /Polish ✗ (Russian)
Gomolka /Polish ✓
Belo /Portuguese ✓
Santos /Portuguese ✓
Rim /Korean ✓
Solomon /French ✓
Agnellutti /Italian ✓
Santana /Portuguese ✓
Ramaker /Dutch ✓
Palmisano /Italian ✓
=======
Epoch : 85 | Loss : 0.2390 | Train Accuracy : 92.80 %
=======
Moraitopoulos /Greek ✓
Rosenberger /German ✓
Torres /Portuguese ✓
Sabbagh /Arabic ✓
Aggelen /Dutch ✓
Chieu /Chinese ✓
Ukhtomsky /Russian ✓
Kouros /Greek ✓
Portyansky /Russian ✓
Dinh /Vietnamese ✓
=======
Epoch : 86 | Loss : 0.2173 | Train Accuracy : 93.15 %
=======
Jaskulski /Polish ✓
Mendez /Spanish ✓
Smyth /English ✓
Mo /Korean ✓
Seegers /Dutch ✓
Elford /English ✓
Lau /Chinese ✓
Sargent /French ✓
Zeman /Czech ✓
Ohme /German ✓
=======
Epoch : 87 | Loss : 0.2189 | Train Accuracy : 93.00 %
=======
Gwang  /Korean ✓
Zhernakov /Russian ✓
Quraishi /Arabic ✓
Asker /Arabic ✓
Franco /Portuguese ✓
Bacon /Czech ✓
Weineltk /Czech ✓
Thuy /Vietnamese ✓
Close /Greek ✓
Xiang /Chinese ✓
=======
Epoch : 88 | Loss : 0.2497 | Train Accuracy : 91.95 %
=======
Basara /Arabic ✓
Esteves /Portuguese ✓
Metz /German ✓
Lopez /Spanish ✓
Bukoski /Polish ✓
Rao /Italian ✓
Klerk /Dutch ✓
Espinoza /Spanish ✓
Wehunt /German ✓
Giehl /German ✓
=======
Epoch : 89 | Loss : 0.2454 | Train Accuracy : 92.70 %
=======
Deniau /French ✓
Bover /Spanish ✗ (Italian)
Soho /Japanese ✓
Ron /Korean ✓
Dolezal /Czech ✓
Yamamura /Japanese ✓
Ramsay /Scottish ✓
Fromm /German ✓
Huerta /Spanish ✓
Colman /Irish ✓
=======
Epoch : 90 | Loss : 0.2432 | Train Accuracy : 92.55 %
=======
Fei /Chinese ✓
Dinh /Vietnamese ✓
Krawiec /Czech ✓
Urbanek /Czech ✓
Yan /Chinese ✓
Giehl /German ✓
Riain /Irish ✓
Zhestkov /Russian ✓
Almetiev /Russian ✓
Deniel /French ✓
=======
Epoch : 91 | Loss : 0.2318 | Train Accuracy : 92.45 %
=======
Macleod /Scottish ✓
Savatier /French ✓
Chong /Chinese ✗ (Korean)
Prchal /Czech ✓
Tsoumada /Greek ✓
Agosti /Italian ✓
Mojjis /Czech ✓
Mitsui /Japanese ✓
San nicolas /Spanish ✓
Kokoris /Greek ✓
=======
Epoch : 92 | Loss : 0.2163 | Train Accuracy : 92.25 %
=======
Marubeni /Japanese ✓
Suh /Korean ✓
Klerks /Dutch ✓
Roma /Spanish ✓
Lac /Vietnamese ✓
Khoury /Arabic ✓
Hoefler /German ✓
Gibson /Scottish ✓
Jasso /Spanish ✓
Oirschotten /Dutch ✓
=======
Epoch : 93 | Loss : 0.2329 | Train Accuracy : 92.90 %
=======
Kikuchi /Japanese ✓
Blecher /German ✓
Ying /Chinese ✓
Nahas /Arabic ✓
Araujo /Portuguese ✓
Koemans /Dutch ✓
Durant /French ✓
Martzenyuk /Russian ✓
Petru /Czech ✓
Wood /Scottish ✓
=======
Epoch : 94 | Loss : 0.2080 | Train Accuracy : 93.35 %
=======
Vespa /Italian ✓
Kowalczyk /Polish ✓
Nahas /Arabic ✓
Tresler /German ✓
Caivano /Italian ✓
Pho /Vietnamese ✓
Dael /Dutch ✓
Heidl /Czech ✓
Totolos /Greek ✓
Adlersflugel /German ✓
=======
Epoch : 95 | Loss : 0.2400 | Train Accuracy : 92.45 %
=======
Zwolenksy /Czech ✓
Chermak /Czech ✓
Sgro /Italian ✓
Lestrange /French ✓
Hwang /Korean ✓
Barros /Spanish ✗ (Portuguese)
Boyle /Scottish ✓
Schmeling /German ✓
Poplawski /Polish ✓
Pantelas /Greek ✓
=======
Epoch : 96 | Loss : 0.2150 | Train Accuracy : 93.10 %
=======
Asher /English ✓
Sai /Vietnamese ✓
Hakimi /Arabic ✓
Sheng /Chinese ✓
Lebedevich /Russian ✓
Castellano /Spanish ✓
Battaglia /Italian ✓
Cardozo /Portuguese ✓
Sinagra /Italian ✓
Bumgarner /German ✓
=======
Epoch : 97 | Loss : 0.2359 | Train Accuracy : 92.80 %
=======
Lyes /English ✓
Do /Vietnamese ✓
Busch /German ✓
Shimura /Japanese ✓
O'Connor /Irish ✓
Geiger /German ✓
Reier /German ✓
Paris /French ✓
Sokolof /Polish ✓
Limarev /Russian ✓
=======
Epoch : 98 | Loss : 0.2369 | Train Accuracy : 92.55 %
=======
Osladil /Czech ✓
Roy /French ✓
Ortega /Spanish ✓
Ruzzier /Italian ✓
Chou /Korean ✓
Mateus /Portuguese ✓
Ibanez /Spanish ✓
Cabello /Spanish ✓
Duguay /French ✓
Yi /Korean ✓
=======
Epoch : 99 | Loss : 0.2192 | Train Accuracy : 92.65 %
=======
Test Accuracy : 94.8000%
""""单独测试"
input_data = lineToTensor('WMN').to(device)
out_data = rnn_name(input_data)
print(out_data)
print(categoryFromOutput(out_data))
"""
tensor([[ 5.7034,  1.0659, -8.1210,  0.5218, -2.5818,  0.1362,  7.4420,  3.9547,1.0824, -7.2981,  4.0036, -2.2944,  1.6835, -3.5377, -7.6178,  9.8920,-0.5789, -1.0545]], device='cuda:0', grad_fn=<AddmmBackward0>)
('Chinese', 15)
"""input_data = lineToTensor('Huang').to(device)
out_data = rnn_name(input_data)
print(out_data)
print(categoryFromOutput(out_data))
"""
tensor([[ 4.1755, -1.2160, -3.8454,  5.4587, -4.6412,  0.8137,  1.2896,  1.7429,-1.3145, -2.1634,  1.0224, -2.7052,  2.1592,  1.1909, -8.0874, 10.2988,-1.9252, -0.0729]], device='cuda:0', grad_fn=<AddmmBackward0>)
('Chinese', 15)
"""

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/378762.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Powershell】超越限制:获取Azure AD登录日志

你是否正在寻找一种方法来追踪 Azure Active Directory&#xff08;Azure AD&#xff09;中用户的登录活动&#xff1f; 如果是的话&#xff0c;查看Azure AD用户登录日志最简单的方法是使用Microsoft Entra管理中心。打开 https://entra.microsoft.com/&#xff0c;然后进入 监…

taro小程序terser-webpack-plugin插件不生效(vue2版本)

背景 最近在做公司内部的小程序脚手架&#xff0c;为了兼容老项目和旧项目&#xff0c;做了vue2taro,vue3taro两个模板&#xff0c;发现terser-webpack-plugin在vue2和vue3中的使用方式并不相同&#xff0c;同样的配置在vue3webpack5中生效&#xff0c;但是在vue2webpack4中就…

学习Python的IDE功能--(一)入门导览

项目视图是主要工具窗口之一。它包含项目目录、SDK 特定的外部库和临时文件。点击带条纹的按钮可以预览演示项目。您也可以按Alt1打开。点击以打开项目视图&#xff0c;展开项目目录以查看项目文件。双击以打开welcome.py。 切换到"学习"工具窗口继续学习本课次。…

ELK企业级日志分析

目 录 一、ELK简介 1.1 elasticsearch简介 1.2 logstash简介 1.3 kibana简介 1.4 ELK的好处 1.5 ELK的工作原理 二、部署ELK 2.1 部署elasticsearch(集群) 2.1.1 修改配置文件 2.1.2 修改系统参数 2.1.2.1 修改systemmd服务管理器 2.1.2.2 性能调优参数 2.1.2.3 …

文献阅读:tidyomics 生态系统:增强组学数据分析

文献介绍 文献题目&#xff1a; The tidyomics ecosystem: enhancing omic data analyses 研究团队&#xff1a; Stefano Mangiola&#xff08;澳大利亚沃尔特和伊丽莎霍尔医学研究所&#xff09;、Michael I. Love&#xff08;美国北卡罗来纳大学教堂山分校&#xff09;、Ant…

k8s集群新增节点

目前集群状态 如K8S 集群搭建中规划的集群一样 Masternode01node02IP192.168.100.100192.168.100.101192.168.100.102OSCent OS 7.9Cent OS 7.9Cent OS 7.9 目前打算新增节点node03 Masternode01node02node03IP192.168.100.100192.168.100.101192.168.100.102192.168.100.1…

Golang | Leetcode Golang题解之第240题搜索二维矩阵II

题目&#xff1a; 题解&#xff1a; func searchMatrix(matrix [][]int, target int) bool {m, n : len(matrix), len(matrix[0])x, y : 0, n-1for x < m && y > 0 {if matrix[x][y] target {return true}if matrix[x][y] > target {y--} else {x}}return f…

STM32 GPIO的工作原理

STM32的GPIO管脚有下面8种可能的配置:&#xff08;4输入 2 输出 2 复用输出) &#xff08;1&#xff09;浮空输入_IN_FLOATING 在上图上&#xff0c;阴影的部分处于不工作状态&#xff0c;尤其是下半部分的输出电路&#xff0c;实际上是与端口处于隔离状态。黄色的高亮部分显示…

C#统一委托Func与Action

C#在System命名空间下提供两个委托Action和Func&#xff0c;这两个委托最多提供16个参数&#xff0c;基本上可以满足所有自定义事件所需的委托类型。几乎所有的 事件 都可以使用这两个内置的委托Action和Func进行处理。 Action委托&#xff1a; Action定义提供0~16个参数&…

stm32入门-----初识stm32

目录 前言 ARM stm32 1.stm32家族 2.stm32的外设资源 3.命名规则 4.系统结构 5.引脚定义 6.启动配置 7.STM32F103C8T6芯片 8.STM32F103C8T6芯片原理图与最小系统电路 前言 已经很久没跟新了&#xff0c;上次发文的时候是好几个月之前了&#xff0c;现在我是想去学习st…

怎样减少视频的容量 怎样减少视频内存保持清晰度

在数字媒体时代&#xff0c;视频内容已经成为人们日常交流和信息传递的重要方式。然而&#xff0c;视频往往占用大量存储空间&#xff0c;给我们的设备带来不小的负担。如何在不损失视频质量的前提下&#xff0c;减少视频文件的大小呢&#xff1f;本文将为你揭秘几个实用的技巧…

定制开发AI智能名片商城微信小程序在私域流量池构建中的应用与策略

摘要 在数字经济蓬勃发展的今天&#xff0c;私域流量已成为企业竞争的新战场。定制开发AI智能名片商城微信小程序&#xff0c;作为私域流量池构建的创新工具&#xff0c;正以其独特的优势助力企业实现用户资源的深度挖掘与高效转化。本文深入探讨了定制开发AI智能名片商城微信…

数据结构(5.2_2)——二叉树的性质

常见考点1: 设非空二叉树中度为0、1和2的结点个数分别为n0、n1和n2&#xff0c;则n0n21(叶子结点比二分支结点多一个) 常见考点2&#xff1a; 二叉树第一层至多右 有个结点(i>1) m叉树第一层至多右 有个结点(i>1) 常见考点3&#xff1a; 高度为h的二叉树至多有个结点…

23年oppo提前批笔试真题-构造二阶行列式

构造二阶行列式 题目描述 小欧希望你构造一个二阶行列式&#xff0c;满足行列式中每个数均为不超过 20 的正整数&#xff0c;且行列式的值恰好等于x。你能帮帮她吗? 输入描述 一个正整数x。-1000 < x < 1000 输出描述 如果无解&#xff0c;请输出-1。否则输出任意合…

ELK日志管理与应用

目录 一.ELK收集nginx日志 二.收集tomcat日志 三.Filebeat 一.ELK收集nginx日志 1.搭建好ELKlogstashkibana架构 2.关闭防火墙和selinux systemctl stop firewalld setenforce 0 3.安装nginx [rootlocalhost ~]# yum install epel-release.noarch -y [rootlocalhost …

好用的AI搜索引擎

1. 360AI 搜索 访问 360AI 搜索: https://www.huntagi.com/sites/1706642948656.html 360AI 搜索介绍&#xff1a; 360AI 搜索&#xff0c;新一代智能答案引擎&#xff0c;值得信赖的智能搜索伙伴&#xff0c;为复杂搜索提供专业支持&#xff0c;解锁更相关、更全面的答案。AI…

Elasticsearch基础(三)

目录 1.DSL查询文档 1.1.DSL查询分类 1.2.全文检索查询 1.3.精准查询 1.4.地理坐标查询 1.5.复合查询 2.搜索结果处理 2.1.排序 2.2.分页 2.3.高亮 2.4.总结 3.RestClient查询文档 3.1.快速入门 3.2.match查询 3.3.精确查询 3.4.布尔查询 3.5.排序、分页 3.6.…

live555 rtsp服务器实战之doGetNextFrame

live555关于RTSP协议交互流程 live555的核心数据结构值之闭环双向链表 live555 rtsp服务器实战之createNewStreamSource live555 rtsp服务器实战之doGetNextFrame 注意&#xff1a;该篇文章可能有些绕&#xff0c;最好跟着文章追踪下源码&#xff0c;不了解源码可能就是天书…

多多OJ评测系统 前端项目环境初始化 安装Vue脚手架 引入Arco Design组件

目录 确定环境 命令行输入 装一下脚手架 监测一下是否安装成功 创建一个项目 选择一系列的配置后 我们打开webStorm 配置脚手架后我们先运行 我们这边能获取到网址 其实我们脚手架已经帮我们做到了 接下来要引入相关的组件 选择用npm进行安装 我们建议的是完整引入…

DETR算法解读——Transformer在目标检测任务的首次应用

论文&#xff1a;End-to-End Object Detection with Transformers 作者&#xff1a;Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko 机构&#xff1a;Facebook AI 链接&#xff1a;https://arxiv.org/abs/2005.12…