Python常用函数
字符串处理
split()
将一个字符串划分成list,划分依据是传入的参数,不传入则默认为空格
txt = "hello my name is Peter"
x = txt.split()
print(x)
>>> ['hello', 'my', 'name', 'is', 'Peter']
x = txt.split("m")
>>> ['hello ', 'y na', 'e is Peter']
strip()
strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
>>> 3210Runoob0123
>>> Runoob
数学类
math.atan2(y,x)
按照先y坐标后x坐标输入,输出x轴正向(水平向右)旋转到该点的角度:逆时针为正,顺时针为负,范围为-pi~pi
>>> math.atan2(1,0)*180/3.14159
89.99999998824843
>>> math.atan2(1,-1)*180/3.1415926
135.00000230285175
tqdm
model.train()
for epoch in range(1, 5):
with tqdm(train_loader, unit="batch") as tepoch: #新增
for data, target in tepoch:
tepoch.set_description(f"Epoch {epoch}") # 新增
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
predictions = output.argmax(dim=1, keepdim=True).squeeze()
loss = F.nll_loss(output, target)
correct = (predictions == target).sum().item()
accuracy = correct / batch_size
loss.backward()
optimizer.step()
tepoch.set_postfix(loss=loss.item(), accuracy=100. * accuracy) #新增
sleep(0.1)
显示结果为:
Epoch 1: 15%|▉ | 142/937 [00:16<01:32, 8.56batch/s, accuracy=89.1, loss=0.341]