# Creating a PyTorch model to fit a curve

import torch
import matplotlib
matplotlib.use(‘TkAgg’)
import matplotlib.pyplot as plt
from torch import nn
import os
import numpy as np

# 从文件中加载数据

if not os.path.isfile(file_path):
raise FileNotFoundError(f"File {file_path} does not exist.")
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’ # 修改为实际路径

# 定义NN模型，继承自nn.Module

class NeuralNetwork(nn.Module):
def init(self):
super(NeuralNetwork, self).init()
# 使用 nn.Parameter 定义待优化的参数
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()

# 训练过程

batches = 5000
plt.figure(“regression”)

def calculate_rmse(predictions, targets):

for i in range(batches):
Vv_pred = model(Ps)
loss = loss_fn(Vv_pred, y)
rmse = calculate_rmse(Vv_pred, y)

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

I would like to know how I can modify to optimize these parameters

Check if any trainable parameters have a valid gradient after the backward pass as it seems your training is stuck.

Below is a partial gradient：Batch 9000
loss: 1.1067631244659424 | RMSE: 1.0520280599594116 | Batch: 9000
Batch 9100
loss: 1.087465524673462 | RMSE: 1.042816162109375 | Batch: 9100
Batch 9200
loss: 1.0683401823043823 | RMSE: 1.0336054563522339 | Batch: 9200
Batch 9300
loss: 1.0493865013122559 | RMSE: 1.0243957042694092 | Batch: 9300
Batch 9400
loss: 1.030604600906372 | RMSE: 1.0151870250701904 | Batch: 9400
Batch 9500
loss: 1.0119946002960205 | RMSE: 1.0059794187545776 | Batch: 9500
Batch 9600
loss: 0.9935567378997803 | RMSE: 0.9967731833457947 | Batch: 9600
Batch 9700
loss: 0.9752906560897827 | RMSE: 0.9875680804252625 | Batch: 9700
Batch 9800