2022李宏毅机器学习hw1

这篇博客详细记录了完成2022年李宏毅机器学习课程作业1的过程,包括数据处理、基础代码实现、模型改进以及可能的优化方向。在基础代码部分,涉及了随机数种子设置、数据集切割、特征选取和模型训练等。在改进方法中,提到了特征选择、神经网络模型优化(如添加BN层)和超参数调整。尽管达到了较强的基线表现,但作者也提出了针对测试集准确率过高、优化方法和训练时间的问题进行进一步研究。
部署运行你感兴趣的模型镜像
Machine Learning HW1 COVID-19 Cases Prediction

一、任务

随机数种子定义,放入gpu
        Given survey results in the past 5 days in a specifific state in U.S., then predict the percentage of new tested positive cases in the 5th day.

 数据

结果

全过strong baselin,public score与bossline差0.01

 二、基础代码

随机数种子定义,放入gpu

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

数据集切割

def 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_size
    train_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)

预测函数

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

数据格式定义

class COVID19Dataset(Dataset):
    '''
    x: Features.
    y: Targets, if none, do prediction.
    '''

    def __init__(self, x, y=None):
        if y is None:
            self.y = y
        else:
            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

特征选取

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

    if select_all:
        feat_idx = list(range(raw_x_train.shape[1]))
    else:
        feat_idx = [0, 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

训练

def trainer(train_loader, valid_loader, model, config, device):
    global aa
    criterion = nn.MSELoss(reduction='mean')  # Define your loss function, do not modify this.
    optimizer = torch.optim.SGD(model.parameters(), lr=config['learning_rate'], momentum=0.9)
    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, 0
    for 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 += 1
            loss_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_loss
            aa = best_loss
            torch.save(model.state_dict(), config['save_path'])  # Save your best model
            print('Saving model with loss {:.3f}...'.format(best_loss))
            early_stop_count = 0
        else:
            early_stop_count += 1

        if 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': True,  # Whether to use all features.
    'valid_ratio': 0.2,  # validation_size = train_size * valid_ratio
    'n_epochs': 3000,  # Number of epochs.
    'batch_size': 256,
    'learning_rate': 1e-5,
    'early_stop': 400,  # If model has not improved for this many consecutive epochs, stop training.
    'save_path': './models/model.ckpt'  # Your model will be saved here.
}

"""# Dataloader
Read data from files and set up training, validation, and testing sets. You do not need to modify this part.
"""

# Set seed for reproducibility
same_seed(config['seed'])
train_data, test_data = pd.read_csv('./covid.train.csv').values, pd.read_csv('./covid.test.csv').values
train_data, valid_data = train_valid_split(train_data, config['valid_ratio'], config['seed'])
print(f"""train_data size: {train_data.shape} 
valid_data size: {valid_data.shape} 
test_data size: {test_data.shape}""")
x_train, x_valid, x_test, y_train, y_valid = select_feat(train_data, valid_data, test_data, config['select_all'])
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)
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)
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']))
preds = predict(test_loader, model, device)
save_pred(preds, 'pred.csv')
print("Loss is {}".format(aa))

三、改进方法

3.1怎么样知道这个特征是好的,排除掉无用特征

def select_feat(train_data, valid_data, test_data, select_all=True):
    '''Selects useful features to perform regression'''
    #选择label
    y_train, y_valid = train_data[:, -1], valid_data[:, -1]

    #获取除最后一列(label)之外的所有行和列。
    raw_x_train, raw_x_valid, raw_x_test = train_data[:, :-1], valid_data[:, :-1], test_data

    #做选择,shape表示维度的维数,shape[0]为第一维,即行数 shape[1]为第二维,即列数
    if select_all:
        feat_idx = list(range(raw_x_train.shape[1]))
    else:
        feat_idx = list(range(1,38))+[38,39,40,41,53,54,55,56,57,69,70,71,72,73,85,86,87,88,89,101,102,103,104,105]  # 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
# device_name = torch.cuda.get_device_name(0)

3.2神经网络模型设计(加BN层,增加隐藏层)

class My_Model(nn.Module):
    def __init__(self, input_dim):
        #子类把父类的__init__()放到自己的__init__()当中,这样子类就有了父类的__init__()的那些东西。
        super(My_Model, self).__init__()
        # TODO: modify model's structure, be aware of dimensions.
        #nn.Sequential() 可以允许将整个容器视为单个模块(即相当于把多个模块封装成一个模块)
        # forward()方法接收输入之后,nn.Sequential()按照内部模块的顺序自动依次计算并输出结果。
        self.layers = nn.Sequential(
            # 线性运算wx+b,输入维度转化成16维度
            nn.Linear(input_dim, 64),
            # nn.BatchNorm1d(64),
            nn.LeakyReLU(0.1),
            nn.Linear(64, 1),
        )
    def forward(self, x):
        x = self.layers(x)
        x = x.squeeze(1)  # (B, 1) -> (B) 去掉维数为1的维度
        return x

    def cal_loss(self, pred, target):
        return torch.sqrt(self.criterion(pred, target))

3.3超参数设计(各层神经元的数量、batch_size的取值、参数更新时的学习率、权值衰减系数或学习的epoch)

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.
    'valid_ratio': 0.2,  # validation_size = train_size * valid_ratio
    'n_epochs': 3000,  # Number of epochs.
    'batch_size': 512,
    'learning_rate': 1e-5,
    'early_stop': 400,  # If model has not improved for this many consecutive epochs, stop training.
    'save_path': './models/model.ckpt'  # Your model will be saved here.
}

3.4优化器改变

#优化算法SGD,带动量的随机梯度下降Momentum-SGD
    optimizer = torch.optim.SGD(model.parameters(), lr=config['learning_rate'], momentum=0.95,weight_decay=0.001)#

四、还可以改进的方向

1.为什么会出现测试集准确率高的问题?

测试集的数据特征比较明显

2.优化方法待改进

数据预处理,调参方法,训练效果可视化分析

3.训练时间过长

使用服务器

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

### 李宏机器学习hw1作业概述 #### 作业目标 李宏机器学习课程的第一份作业旨在帮助学生理解特征选择的重要性以及不同激活函数的效果。通过该作业,参与者能够深入探讨如何挑选最有效的输入变量来构建模型,并评估多种激活函数对于神经网络性能的影响[^1]。 #### 主要强化点 #### 特征选择 在处理数据集时,不是所有的属性都对预测有贡献;有些可能引入噪声或冗余信息。因此,在训练之前进行合理的特征工程是非常重要的一步。本作业鼓励探索不同的方法来进行特征筛选,比如基于统计测试、递归消除法或是利用正则化技术等手段找出最具代表性的子集。 #### 激活函数的选择 另一个重点在于实验各种类型的激活函数——线性/非线性变换可以极大地影响深层架构的学习能力。常见的选项包括Sigmoid, ReLU及其变体(LeakyReLU)、tanh等等。通过对这些候选者进行全面比较分析,可以获得有关它们各自优缺点的认识并作出明智决策以优化最终表现。 ```python import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # 加载鸢尾花数据集作为示例 data = load_iris() X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2) scaler = StandardScaler().fit(X_train) scaled_X_train = scaler.transform(X_train) scaled_X_test = scaler.transform(X_test) model = Sequential([ Dense(64, activation='relu', input_shape=(4,)), # 使用ReLU激活函数 Dense(3, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) history = model.fit(scaled_X_train, y_train, epochs=50, batch_size=8, validation_data=(scaled_X_test, y_test)) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦想的小鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值