pytorch—波士顿房价问题

该博客展示了使用PyTorch构建并训练一个神经网络模型来预测波士顿房价的过程。首先定义了一个包含隐藏层和线性回归层的网络结构,然后加载预训练的模型,并计算测试集上的损失。接着,博主训练了模型,通过Adam优化器调整参数,输出了训练过程中的损失及部分预测结果,并最终在测试集上评估了模型性能。
摘要由CSDN通过智能技术生成
import torch
import torch
import re
class Net(torch.nn.Module):
    def __init__(self,n_feature,n_output):#初始化,
        super(Net,self).__init__()#继承父类
        self.hidden = torch.nn.Linear(n_feature,100)
        self.predict = torch.nn.Linear(100,n_output) #回归模型
    def forward(self,x):
        out = self.hidden(x)
        out = torch.relu(out)
        out = self.predict(out)
        return out
import numpy as np
import pandas as pd
#data
data_path = "boston_house_prices.csv"
reader = pd.read_csv(data_path)
data = np.array(reader)
Y = data[:,-1]
X = data[:,0:-1]
X_train = X[0:496,...]
Y_train = Y[0:496,...]
X_test = X[496:,...]
Y_test = Y[496:,...]


print(Y_test.shape)
print(X_test.shape)
net = torch.load("model/model.pkl")
loss_func = torch.nn.MSELoss()
x_data = torch.tensor(X_test, dtype=torch.float32)
y_data = torch.tensor(Y_test, dtype=torch.float32)
pred = net.forward(x_data)
pred =torch.squeeze(pred)
loss_test = loss_func(pred, y_data) * 0.001
print("loss_test:{}".format(loss_test))
import torch
import re

import numpy as np
import pandas as pd
#data
data_path = "boston_house_prices.csv"
reader = pd.read_csv(data_path)
data = np.array(reader)
Y = data[:,-1]
X = data[:,0:-1]
X_train = X[0:496,...]
Y_train = Y[0:496,...]
X_test = X[496:,...]
Y_test = Y[496:,...]
print(Y_test.shape)
print(X_test.shape)
# gouzhao net

```cpp
class Net(torch.nn.Module):
    def __init__(self,n_feature,n_output):#初始化,
        super(Net,self).__init__()#继承父类
        self.hidden = torch.nn.Linear(n_feature,100)
        self.predict = torch.nn.Linear(100,n_output) #回归模型
    def forward(self,x):
        out = self.hidden(x)
        out = torch.relu(out)
        out = self.predict(out)
        return out

net = Net(13,1)
#loss
loss_func = torch.nn.MSELoss()
#optimiter
optimizer = torch.optim.Adam(net.parameters(), lr = 0.01)
#training
for i in range(10000):
    x_data = torch.tensor(X_train,dtype=torch.float32)
    y_data = torch.tensor(Y_train, dtype=torch.float32)
    pred = net.forward(x_data)
    pred = torch.squeeze(pred)
    loss = loss_func(pred, y_data)*0.001

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print("ite:{},loss_train:{}".format(i,loss))
    print(pred[0:10])
    print(y_data[0:10])

#test
    x_data = torch.tensor(X_test, dtype=torch.float32)
    y_data = torch.tensor(Y_test, dtype=torch.float32)
    pred = net.forward(x_data)
    pred =torch.squeeze(pred)
    loss_test = loss_func(pred, y_data) * 0.001
    print("ite:{},loss_test:{}".format(i, loss_test))
#draw loss picture
torch.save(net,"model/model.pkl")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值