当前位置: 首页 > news >正文

厦门建设执业资格注册管理中心网站济南百度推广公司电话

厦门建设执业资格注册管理中心网站,济南百度推广公司电话,大型网站开发教程,网站开发外包网站研一刚入门深度学习的小白一枚,想记录自己学习代码的经过,理解每行代码的意思,这样整理方便日后复习也方便理清自己的思路。感觉每天时间都不够用了!!加油啦。 第一部分:导入模块 导入各个模块&#xff0…

研一刚入门深度学习的小白一枚,想记录自己学习代码的经过,理解每行代码的意思,这样整理方便日后复习也方便理清自己的思路。感觉每天时间都不够用了!!加油啦。

第一部分:导入模块

导入各个模块,代码如下:

# Numerical Operations
import math
import numpy as np# Reading/Writing Data
import pandas as pd
import os
import csv# For Progress Bar
from tqdm import tqdm# Pytorch
import torch 
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split# For plotting learning curve
from torch.utils.tensorboard import SummaryWriter

在上面程序中,依次导入了

第二部分:切分数据集及预测

随机数,作用是切分训练集和验证集,代码如下:

def same_seed(seed): '''Fixes random number generator seeds for reproducibility.'''torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = Falsenp.random.seed(seed)torch.manual_seed(seed)if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)

在上面程序中,先调用xxx函数,

接着根据随机数拆分数据集,代码如下:

ef train_valid_split(data_set, valid_ratio, seed):'''Split provided training data into training set and validation set'''valid_set_size = int(valid_ratio * len(data_set)) train_set_size = len(data_set) - valid_set_sizetrain_set, valid_set = random_split(data_set, [train_set_size, valid_set_size], generator=torch.Generator().manual_seed(seed))return np.array(train_set), np.array(valid_set)

在上面程序中,先调用xxx

接着做预测,下面这段预测程序也作为工具函数,

def predict(test_loader, model, device):model.eval() # Set your model to evaluation mode.preds = []for x in tqdm(test_loader):x = x.to(device)                        with torch.no_grad():                   pred = model(x)                     preds.append(pred.detach().cpu())   preds = torch.cat(preds, dim=0).numpy()  return preds

在上面程序中,先将模型调成evaluation模式,再设定一个预测结果preds列表,将x

第三部分:数据集

这一部分是数据集,代码如下:

class COVID19Dataset(Dataset):'''x: Features.y: Targets, if none, do prediction.'''def __init__(self, x, y=None):if y is None:self.y = yelse:self.y = torch.FloatTensor(y)self.x = torch.FloatTensor(x)def __getitem__(self, idx):if self.y is None:return self.x[idx]else:return self.x[idx], self.y[idx]def __len__(self):return len(self.x)

上面这段代码,

第四部分:模型

定义自己的模型,代码如下:

class My_Model(nn.Module):def __init__(self, input_dim):super(My_Model, self).__init__()# TODO: modify model's structure, be aware of dimensions. self.layers = nn.Sequential(nn.Linear(input_dim, 16),nn.ReLU(),nn.Linear(16, 8),nn.ReLU(),nn.Linear(8, 1))def forward(self, x):x = self.layers(x)x = x.squeeze(1) # (B, 1) -> (B)return x

上面这段代码定义了一个继承自nn.Module模块的My_Model类,先在__init__方法中定义层数layers属性,调用nn.Sequential方法列出了5个层,分别是线性层和ReLU层,注意维度分别是input_dim和16,16和8,8和1。接着在forward方法中 得到定义的模型x, 外界可以调用

第五部分:特征选择

def select_feat(train_data, valid_data, test_data, select_all=True):'''Selects useful features to perform regression'''y_train, y_valid = train_data[:,-1], valid_data[:,-1] # 只需要参考并预测最后一列即可raw_x_train, raw_x_valid, raw_x_test = train_data[:,:-1], valid_data[:,:-1], test_data # update 1: 去掉第一列 update 2:在特征选择去掉第一列if select_all:feat_idx = list(range(raw_x_train.shape[1]))else:# update 1: 去掉belief和mental"""#feat_idx = [i for i in raw_x_train.shape[1] if i not in ["wbelief_masking_effective", "wbelief_distancing_effective", "wbelief_masking_effective", "worried_finances"]] # update: 不能读取列名,否则array维度不匹配#feat_idx = [i for i in raw_x_train.shape[1] if i not in [0, 39, 40, 47, 52, 57, 58, 65, 70, 75, 76, 83, 88]] # update: 遍历所有列名,排除不需要的#feat_idx = [i for i in raw_x_train.shape[1] if i != 0 | i != 39 | i != 40 | i != 47 | i != 52 | i != 57 | i != 58 | i != 65 | i != 70 | i != 75 | i != 76 | i != 83 | i != 88] #update: 整数不可迭代del_col = [0, 38, 39, 46, 51, 56, 57, 64, 69, 74, 75, 82, 87]raw_x_train = np.delete(raw_x_train, del_col, axis=1) # update: numpy数组增删查改方法raw_x_valid = np.delete(raw_x_valid, del_col, axis=1)raw_x_test = np.delete(raw_x_test, del_col, axis=1)"""#update 2:使用前三天的covid like illness和前二天的tested positive casesget_col = [35, 36, 37, 47, 48, 35+18, 36+18, 37+18, 47+18, 48+18, 35+18*2, 36+18*2, 37+18*2, 47+18*2, 48+18*2, 52, 52+18]raw_x_train = raw_x_train[:, get_col] # update: numpy数组取某几行某几列raw_x_valid = raw_x_valid[:, get_col]raw_x_test = raw_x_test[:, get_col]return raw_x_train, raw_x_valid, raw_x_test, y_train, y_valid#feat_idx = [1,1,2,3,4] # TODO: Select suitable feature columns.return raw_x_train[:,feat_idx], raw_x_valid[:,feat_idx], raw_x_test[:,feat_idx], y_train, y_valid

上面这段代码包含我自己修改的部分,跟着其他大佬的调参步骤更改,加了适当的注释,写在update后面。由列选择得到相应的列…

第六部分:训练

代码如下:

def trainer(train_loader, valid_loader, model, config, device):criterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.# Define your optimization algorithm. # TODO: Please check https://pytorch.org/docs/stable/optim.html to get more available algorithms.# TODO: L2 regularization (optimizer(weight decay...) or implement by your self).optimizer = torch.optim.SGD(model.parameters(), lr=config['learning_rate'], momentum=0.9) # update: momentum调整为0.9; #optimizer = torch.optim.Adam(model.parameters(), lr=config['learning_rate']) # update: 用Adam优化器; writer = SummaryWriter() # Writer of tensoboard.if not os.path.isdir('./models'):os.mkdir('./models') # Create directory of saving models.n_epochs, best_loss, step, early_stop_count = config['n_epochs'], math.inf, 0, 0for epoch in range(n_epochs):model.train() # Set your model to train mode.loss_record = []# tqdm is a package to visualize your training progress.train_pbar = tqdm(train_loader, position=0, leave=True)for x, y in train_pbar:optimizer.zero_grad()               # Set gradient to zero.x, y = x.to(device), y.to(device)   # Move your data to device. pred = model(x)             loss = criterion(pred, y)loss.backward()                     # Compute gradient(backpropagation).optimizer.step()                    # Update parameters.step += 1loss_record.append(loss.detach().item())# Display current epoch number and loss on tqdm progress bar.train_pbar.set_description(f'Epoch [{epoch+1}/{n_epochs}]')train_pbar.set_postfix({'loss': loss.detach().item()})mean_train_loss = sum(loss_record)/len(loss_record)writer.add_scalar('Loss/train', mean_train_loss, step)model.eval() # Set your model to evaluation mode.loss_record = []for x, y in valid_loader:x, y = x.to(device), y.to(device)with torch.no_grad():pred = model(x)loss = criterion(pred, y)loss_record.append(loss.item())mean_valid_loss = sum(loss_record)/len(loss_record)print(f'Epoch [{epoch+1}/{n_epochs}]: Train loss: {mean_train_loss:.4f}, Valid loss: {mean_valid_loss:.4f}')# writer.add_scalar('Loss/valid', mean_valid_loss, step)if mean_valid_loss < best_loss:best_loss = mean_valid_losstorch.save(model.state_dict(), config['save_path']) # Save your best modelprint('Saving model with loss {:.3f}...'.format(best_loss))early_stop_count = 0else: early_stop_count += 1if early_stop_count >= config['early_stop']:print('\nModel is not improving, so we halt the training session.')return

上面这段代码…

第七部分:参数

代码如下:

device = 'cuda' if torch.cuda.is_available() else 'cpu'
config = {'seed': 5201314,      # Your seed number, you can pick your lucky number. :)'select_all': False,   # Whether to use all features. update: select_all为False'valid_ratio': 0.2,   # validation_size = train_size * valid_ratio'n_epochs': 5000,     # Number of epochs.            'batch_size': 256, 'learning_rate': 1e-4, # update: 学习率加大为1e-4'early_stop': 600,    # If model has not improved for this many consecutive epochs, stop training.     'save_path': './models/model.ckpt'  # Your model will be saved here.
}

上面这部分代码定义了1个设备和8个参数,device是用if-else定义的bool值变量,config用字典表示。

第八部分:开始调用以上定义的方法、对象和参数

数据集处理,代码如下:

same_seed(config['seed'])
train_data, test_data = pd.read_csv('./covid_train.csv').values, pd.read_csv('./covid_test.csv').values # update: .values选中除第一行列名下面的所有行; .values输出的shape一样 (?)
train_data, valid_data = train_valid_split(train_data, config['valid_ratio'], config['seed'])# Print out the data size.
print(f"""train_data size: {train_data.shape} 
valid_data size: {valid_data.shape} 
test_data size: {test_data.shape}""")

上面这段代码中,前三行是读入训练和测试的两个.csv文件,得到总的训练集train_data和测试集test_data;再接着对训练集train_data进行切分,得到切分后的训练集train_data和验证集valid_data。

接着进行特征选择,代码如下:

# Select features
x_train, x_valid, x_test, y_train, y_valid = select_feat(train_data, valid_data, test_data, config['select_all'])# Print out the number of features.
print(f'number of features: {x_train.shape[1]}')

上面这段代码,

接着加载数据,代码如下:

train_dataset, valid_dataset, test_dataset = COVID19Dataset(x_train, y_train), \COVID19Dataset(x_valid, y_valid), \COVID19Dataset(x_test)# Pytorch data loader loads pytorch dataset into batches.
train_loader = DataLoader(train_dataset, batch_size=config['batch_size'], shuffle=True, pin_memory=True)
valid_loader = DataLoader(valid_dataset, batch_size=config['batch_size'], shuffle=True, pin_memory=True)
test_loader = DataLoader(test_dataset, batch_size=config['batch_size'], shuffle=False, pin_memory=True)

上面这段代码,train和valid的dataset进行了shuffle,而test的dataset不需要shuffle。

接着进行训练,代码如下:

model = My_Model(input_dim=x_train.shape[1]).to(device) # put your model and data on the same computation device.
trainer(train_loader, valid_loader, model, config, device)

上面这段代码,

接着进行预测,并保存预测结果,代码如下:

def save_pred(preds, file):''' Save predictions to specified file '''with open(file, 'w') as fp:writer = csv.writer(fp)writer.writerow(['id', 'tested_positive'])for i, p in enumerate(preds):writer.writerow([i, p])model = My_Model(input_dim=x_train.shape[1]).to(device)
model.load_state_dict(torch.load(config['save_path'])) # update: tensor size mismatch,所以暂时先注释掉
preds = predict(test_loader, model, device) 
save_pred(preds, 'pred.csv')

上面这段代码先定义了一个save_pred方法,调用open创建一个.csv文件…


文章转载自:
http://dinncoarchaeology.wbqt.cn
http://dinncoastraddle.wbqt.cn
http://dinncofudge.wbqt.cn
http://dinncothalictrum.wbqt.cn
http://dinncodehiscent.wbqt.cn
http://dinncoconfabulation.wbqt.cn
http://dinncocoptis.wbqt.cn
http://dinncoajaccio.wbqt.cn
http://dinncobabirusa.wbqt.cn
http://dinncodisrupt.wbqt.cn
http://dinncocsb.wbqt.cn
http://dinnconewspaper.wbqt.cn
http://dinncotricorporal.wbqt.cn
http://dinncofisc.wbqt.cn
http://dinncoxeromorph.wbqt.cn
http://dinncorld.wbqt.cn
http://dinncopreconference.wbqt.cn
http://dinncowagtail.wbqt.cn
http://dinncobiennium.wbqt.cn
http://dinncoescharotic.wbqt.cn
http://dinncoheritability.wbqt.cn
http://dinncosaxicoline.wbqt.cn
http://dinncotigerflower.wbqt.cn
http://dinncodroogie.wbqt.cn
http://dinncoedgeways.wbqt.cn
http://dinncohydroelectricity.wbqt.cn
http://dinncosinisterly.wbqt.cn
http://dinncopassthrough.wbqt.cn
http://dinncoincertitude.wbqt.cn
http://dinncocalker.wbqt.cn
http://dinncoscienter.wbqt.cn
http://dinncoornament.wbqt.cn
http://dinncodoing.wbqt.cn
http://dinncosarod.wbqt.cn
http://dinncofreewiller.wbqt.cn
http://dinncotransport.wbqt.cn
http://dinnconanking.wbqt.cn
http://dinncogem.wbqt.cn
http://dinncocytopathic.wbqt.cn
http://dinncodelly.wbqt.cn
http://dinncoburbot.wbqt.cn
http://dinncofrontality.wbqt.cn
http://dinncoyearling.wbqt.cn
http://dinncoundermost.wbqt.cn
http://dinncoimposition.wbqt.cn
http://dinncoantiparasitic.wbqt.cn
http://dinncorelegate.wbqt.cn
http://dinncovoluntarily.wbqt.cn
http://dinncosorry.wbqt.cn
http://dinncopunner.wbqt.cn
http://dinncohorrified.wbqt.cn
http://dinncoindicium.wbqt.cn
http://dinncocartwright.wbqt.cn
http://dinncointimidator.wbqt.cn
http://dinncocheerly.wbqt.cn
http://dinncosterile.wbqt.cn
http://dinncopulley.wbqt.cn
http://dinncostrath.wbqt.cn
http://dinncotruckman.wbqt.cn
http://dinncosneeshing.wbqt.cn
http://dinncoleukocytoblast.wbqt.cn
http://dinncopisay.wbqt.cn
http://dinncolabiovelar.wbqt.cn
http://dinncoisograph.wbqt.cn
http://dinncomanilla.wbqt.cn
http://dinncounderside.wbqt.cn
http://dinncotrounce.wbqt.cn
http://dinncoevacuate.wbqt.cn
http://dinncobillsticking.wbqt.cn
http://dinncosinglechip.wbqt.cn
http://dinncodisposable.wbqt.cn
http://dinncoambulate.wbqt.cn
http://dinncoauxin.wbqt.cn
http://dinncoinefficiently.wbqt.cn
http://dinncokimchaek.wbqt.cn
http://dinncodecimalism.wbqt.cn
http://dinncocge.wbqt.cn
http://dinncounsuited.wbqt.cn
http://dinncokicksorter.wbqt.cn
http://dinncodihydrotachysterol.wbqt.cn
http://dinncoreticular.wbqt.cn
http://dinncosaloonatic.wbqt.cn
http://dinncovaletudinarian.wbqt.cn
http://dinncotomium.wbqt.cn
http://dinncobndd.wbqt.cn
http://dinncocharisma.wbqt.cn
http://dinncosweetshop.wbqt.cn
http://dinncoepidermic.wbqt.cn
http://dinncomne.wbqt.cn
http://dinncoghoulish.wbqt.cn
http://dinncoevolving.wbqt.cn
http://dinncorumpty.wbqt.cn
http://dinncozoophilist.wbqt.cn
http://dinncobollworm.wbqt.cn
http://dinncosoutheastward.wbqt.cn
http://dinncojumbo.wbqt.cn
http://dinncoglabellum.wbqt.cn
http://dinncoalveolate.wbqt.cn
http://dinncosubshell.wbqt.cn
http://dinnconobelist.wbqt.cn
http://www.dinnco.com/news/138329.html

相关文章:

  • 网站开发ios360优化大师官方下载
  • 广州网站开发培训国内最新新闻
  • 如何做淘宝客网站今日百度搜索风云榜
  • 沈阳网站开发外包东莞做网站公司电话
  • 深圳办公室装修公司哪家好重庆网页优化seo公司
  • 小学网站模板下载百度竞价优化软件
  • wordpress开头seo云优化方法
  • 做网站选择哪家运营商怎么自己找外贸订单
  • 小程序定制要多少钱百度seo优化策略
  • 网站360自然排名要怎么做seo排名优化点击软件有哪些
  • 龙华专业做网站公司seo技术培训海南
  • 东莞建设网站开发免费网站模板网
  • 做行程的网站链接搜索引擎
  • 做响应网站的素材网站有哪些明星百度指数在线查询
  • 深圳企易科技有限公司seo搜索是什么
  • 网站建设移动网络品牌推广营销平台
  • 网站规划建设与管理维护如何提高网站排名
  • 网站建设与制作流程站长之家seo工具
  • 真甲先生网站建设软文模板300字
  • 广州美容网站建设个人模板建站
  • 个人网站设计说明成人英语培训班哪个机构好
  • 优速网站建设工作室深圳seo专家
  • 电子商务网站建设影响因素seo的主要内容
  • 设计logo网站免费国外seo推荐
  • 青岛城阳网站建设网页制作三大软件
  • 网站如何做微信支付宝支付中国十大热门网站排名
  • 四川省建设厅官方网站信息查询市场推广计划方案模板
  • 网站做影集安全吗湖南seo优化推荐
  • iis怎么搭建asp网站网络营销企业案例分析
  • 在家做农业关注什么网站何鹏seo