pytorch预测房价

import numpy as np
import pandas as pd
import torch
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt

# 读取训练集数据
train_data = pd.read_csv('../data/train.csv')
# 读取测试集数据
test_data = pd.read_csv('../data/test.csv')
# 打印数据集大小
# print(train_data.shape)
# print(test_data.shape)

# 数据预处理。训练集数据删除第一行ID和最后一行的目标价格,测试集数据删除第一行ID,结果合并后作为特征
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
#print(all_features.dtypes)
# 获取非object类型的数据列索引
features_index = all_features.dtypes[all_features.dtypes != 'object'].index
# 标准化数据
all_features[features_index] = all_features[features_index].apply(lambda x: (x - x.mean()) / x.std())
# 将缺失值(NaN)设置为0
all_features[features_index] = all_features[features_index].fillna(0)
# 独热编码
all_features = pd.get_dummies(all_features, dummy_na=True)
print(all_features.shape)

# 获取训练数据集行数
train_count = train_data.shape[0]
print(train_count)
# 获取训练数据集的特征
train_features = torch.tensor(all_features[:train_count].values, dtype=torch.float32)
# 获取测试数据集的特征
test_features = torch.tensor(all_features[train_count:].values, dtype=torch.float32)
# 获取训练数据集的标签
train_labels = torch.tensor(train_data.SalePrice.values.reshape(-1, 1), dtype=torch.float32)

# 损失函数定义为均方损失函数
loss_function = nn.MSELoss()

# 多层感知器模型
class Net(nn.Module):
    def __init__(self, in_features):
        super(Net, self).__init__()
        self.linear_relu1 = nn.Linear(in_features, 128) # 输入层
        self.linear_relu2 = nn.Linear(128, 256) # 隐藏层
        self.linear_relu3 = nn.Linear(256, 256) # 隐藏层
        self.linear_relu4 = nn.Linear(256, 256) # 隐藏层
        self.linear5 = nn.Linear(256, 1) # 输出层

    def forward(self, x):
        y_pred = self.linear_relu1(x)
        y_pred = nn.functional.relu(y_pred)

        y_pred = self.linear_relu2(y_pred)
        y_pred = nn.functional.relu(y_pred)

        y_pred = self.linear_relu3(y_pred)
        y_pred = nn.functional.relu(y_pred)

        y_pred = self.linear_relu4(y_pred)
        y_pred = nn.functional.relu(y_pred)

        y_pred = self.linear5(y_pred)
        return y_pred

multilayer_perceptrons_model = Net(train_features.shape[1])

# 损失函数:对数均方函数
def log_rmse(net, features, labels):
    # 将模型输出结果中小于1的值设置为1。目的是为了在取对数时进一步稳定结果
    clipped_preds = torch.clamp(net(features), 1, float('inf'))
    rmse = torch.sqrt(loss_function(torch.log(clipped_preds), torch.log(labels)))
    return rmse.item()

# 模型训练
def train(net, train_features, train_labels, test_features, test_labels,
          num_epochs, learning_rate, weight_decay, batch_size):
    train_ls, test_ls = [], []
    train_iter = d2l.load_array((train_features, train_labels), batch_size)
    # 优化器使用Adam优化算法
    optimizer = torch.optim.Adam(net.parameters(), lr = learning_rate, weight_decay = weight_decay)

    # 模型迭代训练
    for epoch in range(num_epochs):
        # 训练一组参数?
        for X, y in train_iter:
            optimizer.zero_grad()
            loss = loss_function(net(X), y)
            loss.backward()
            optimizer.step()
        train_ls.append(log_rmse(net, train_features, train_labels))
        if test_labels is not None:
            test_ls.append(log_rmse(net, test_features, test_labels))
    
    return train_ls, test_ls

# 获取K折交叉验证数据集。将训练集数据氛围k份,其中第i份用作验证数据,其余用作训练数据
def get_k_fold_data(k, i, X, y):
    assert k > 1
    fold_size = X.shape[0] // k # 整除k
    X_train, y_train = None, None
    for j in range(k):
        idx = slice(j * fold_size, (j + 1) * fold_size)
        X_part, y_part = X[idx, :], y[idx]
        if j == i:
            X_valid, y_valid = X_part, y_part
        elif X_train is None:
            X_train, y_train = X_part, y_part
        else:
            X_train = torch.cat([X_train, X_part], 0)
            y_train = torch.cat([y_train, y_part], 0)
    return X_train, y_train, X_valid, y_valid

# 基于K折交叉验证数据集执行K次训练
def k_fold_train(k, X_train, y_train, num_epochs, learning_rate, weight_decay, batch_size):
    train_l_sum, valid_l_sum = 0, 0
    for i in range(k):
        # data = get_k_fold_data(k, i, X_train, y_train)
        train_features, train_labels, valid_features, valid_labels = get_k_fold_data(k, i, X_train, y_train)
        # 这个*data是几个意思???
        # train_ls, valid_ls = train(net, *data, num_epochs, learning_rate, weight_decay, batch_size)
        train_ls, valid_ls = train(multilayer_perceptrons_model, train_features, train_labels, valid_features, valid_labels, num_epochs, learning_rate, weight_decay, batch_size)
        train_l_sum += train_ls[-1]
        valid_l_sum += valid_ls[-1]
        # 绘制子图
        plt.subplot(2, 3, i + 1)
        train_line, = plt.plot(list(range(1, num_epochs + 1)), train_ls)
        valid_line, = plt.plot(valid_ls)        
        plt.xlabel("epoch")
        plt.ylabel("rmse")
        # plt.yscale('log')
        plt.title('#{} fold result'.format(i + 1))
        plt.legend([train_line, valid_line], ['train', 'valid'], loc='best')
        plt.grid(False)
        print(f'折{i + 1}, 训练log rmse={float(train_ls[-1]):f}, '
              f'验证log rmse={float(valid_ls[-1]):f}')
    return train_l_sum / k, valid_l_sum / k

k = 5
num_epochs = 100
lr = 1e-4
weight_decay = 0
batch_size = 64
# 训练
train_l, valid_l = k_fold_train(k, train_features, train_labels, num_epochs, lr, weight_decay, batch_size)
print(f'{k}-折验证:平均训练log rmse:{float(train_l):f}, '
      f'平均验证log rmse:{float(valid_l):f}')

# 保存模型参数
torch.save(multilayer_perceptrons_model.state_dict(), 'model_param')

# 显示绘图
plt.tight_layout()
plt.show()
  • 环境

OS: macOS 12.1

pytorch: 1.10.1

  • C++调用pytorch模型

  • 模型实现

import torch

# 多层感知器模型
# class Net(torch.jit.ScriptModule):
class Net(torch.nn.Module):
    def __init__(self, in_features):
        super(Net, self).__init__()
        self.linear_relu1 = torch.nn.Linear(in_features, 128) # 输入层
        self.linear_relu2 = torch.nn.Linear(128, 256) # 隐藏层
        self.linear_relu3 = torch.nn.Linear(256, 256) # 隐藏层
        self.linear_relu4 = torch.nn.Linear(256, 256) # 隐藏层
        self.linear5 = torch.nn.Linear(256, 1) # 输出层

    def forward(self, input):
        y_pred = self.linear_relu1(input)
        y_pred = torch.nn.functional.relu(y_pred)

        y_pred = self.linear_relu2(y_pred)
        y_pred = torch.nn.functional.relu(y_pred)

        y_pred = self.linear_relu3(y_pred)
        y_pred = torch.nn.functional.relu(y_pred)

        y_pred = self.linear_relu4(y_pred)
        y_pred = torch.nn.functional.relu(y_pred)

        y_pred = self.linear5(y_pred)
        return y_pred

# 模型实例。特征数:331
my_model = Net(331)

scripted_model = torch.jit.script(my_model)
print(scripted_model)
print(scripted_model.code)

# 加载预训练的参数
scripted_model.load_state_dict(torch.load('model_param'))
# 进入预测模式
scripted_model.eval()

# 模型序列化
scripted_model.save("model.pt")
  • C++调用模型

#include <torch/script.h>
#include <iostream>
using namespace std;

int main(int argc, const char* argv[])
{
    if (argc != 2) {
        cerr << "usage: example_app <path-to-exported-script-module>" << endl;
        return -1;
    }

    auto model = torch::jit::load(argv[1]); // torch::jit::Module

    cout << "load OK!" << endl;
    return 0;
}
  • CMake

创建以下CMakeLists.txt文件

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example)

find_package(Torch REQUIRED)

message(STATUS "TORCH_LIBRARIES = ${TORCH_LIBRARIES}")

set(mkl_include /opt/intel/oneapi/mkl/2022.0.0/include)
set(mkl_lib /opt/intel/oneapi/mkl/2022.0.0/lib)
include_directories(${mkl_include})
link_directories(${mkl_lib})

add_executable(example_app example_app.cpp)
target_link_libraries(example_app "${TORCH_LIBRARIES}" libmkl_intel_ilp64.dylib)
set_property(TARGET example_app PROPERTY CXX_STANDARD 14)

mkl的使用还有问题,待修正。。。

参考文献:

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值