import torch
import matplotlib
matplotlib.use(‘TkAgg’)
import matplotlib.pyplot as plt
from torch import nn
import os
import numpy as np
从文件中加载数据
def load_data_from_file(file_path):
if not os.path.isfile(file_path):
raise FileNotFoundError(f"File {file_path} does not exist.")
data = np.loadtxt(file_path)
x = torch.tensor(data[:, 0], dtype=torch.float32) # 第一列
Ps = torch.tensor(data[:, 1], dtype=torch.float32) # 第二列
y = torch.tensor(data[:, 2], dtype=torch.float32) # 第三列
return x, Ps, y
加载数据
file_path = ‘D:/2-test/data.txt’ # 修改为实际路径
x, Ps, y = load_data_from_file(file_path)
定义NN模型,继承自nn.Module
class NeuralNetwork(nn.Module):
def init(self):
super(NeuralNetwork, self).init()
# 使用 nn.Parameter 定义待优化的参数
self.N0 = nn.Parameter(torch.tensor(1.0, dtype=torch.float32), requires_grad=True)
self.Pn0 = nn.Parameter(torch.tensor(1.0, dtype=torch.float32), requires_grad=True)
self.P1 = nn.Parameter(torch.tensor(1.0, dtype=torch.float32), requires_grad=True)
self.Pg0 = nn.Parameter(torch.tensor(1.0, dtype=torch.float32), requires_grad=True)
self.eta = nn.Parameter(torch.tensor(1.0, dtype=torch.float32), requires_grad=True)
self.Rn = torch.tensor(3.1e-10, dtype=torch.float32) # 固定值
self.Vv0 = nn.Parameter(torch.tensor(0.1, dtype=torch.float32), requires_grad=True) # 初始孔洞体积
def forward(self, Ps):
dt = 1e-12
# 计算成核率
N_dot = torch.where(Ps > self.Pn0, self.N0 * torch.exp((Ps - self.Pn0) / self.P1), torch.tensor(0.0, dtype=torch.float32))
# 计算孔洞成核体积
Delta_Vn = (8 * torch.pi * N_dot * dt * self.Rn ** 3)
# 计算孔洞生长体积
Vg = self.Vv0 * 3 / 4 * (Ps - self.Pg0) / self.eta * dt
# 总体积
Vv = Vg + Delta_Vn
return Vv
创建模型
model = NeuralNetwork()
定义损失函数和优化器
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
训练过程
batches = 5000
plt.figure(“regression”)
def calculate_rmse(predictions, targets):
return torch.sqrt(loss_fn(predictions, targets))
for i in range(batches):
Vv_pred = model(Ps)
loss = loss_fn(Vv_pred, y)
rmse = calculate_rmse(Vv_pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i % 100 == 0:
loss_value = loss.item()
rmse_value = rmse.item()
print(f'loss: {loss_value} | RMSE: {rmse_value} | Batch: {i}')
plt.cla()
plt.plot(x.numpy(), y.numpy(), label='Actual')
plt.plot(x.numpy(), Vv_pred.detach().numpy(), label='Predicted')
plt.legend()
plt.draw()
plt.pause(0.01)
关闭交互模式
plt.ioff()
plt.cla()
plt.plot(x.numpy(), y.numpy(), label=‘Actual’)
plt.plot(x.numpy(), Vv_pred.detach().numpy(), label=‘Predicted’)
plt.legend()
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.title(‘Final Regression Result’)
plt.savefig(“final_plot.png”)
plt.show()
打印模型参数
print(“N0:”, model.N0.item())
print(“Pn0:”, model.Pn0.item())
print(“P1:”, model.P1.item())
print(“Pg0:”, model.Pg0.item())
print(“eta:”, model.eta.item())
But this code doesn’t optimize the parameters, here’s the result:
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2300
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2400
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2500
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2600
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2700
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2800
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 2900
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3000
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3100
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3200
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3300
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3400
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3500
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3600
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3700
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3800
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 3900
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4000
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4100
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4200
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4300
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4400
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4500
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4600
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4700
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4800
loss: 0.10101878643035889 | RMSE: 0.3178345263004303 | Batch: 4900
N0: 1.0
Pn0: 1.0
P1: 1.0
Pg0: 1.0
eta: 1.0
进程已结束,退出代码 0
I would like to know how I can modify to optimize these parameters