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")