|
import torch |
|
import torch.nn as nn |
|
from tqdm import tqdm |
|
import torch.optim as optim |
|
|
|
|
|
|
|
data = [ |
|
[2, 1, 7, 6.0], |
|
[3, 2, 6, 7.5], |
|
[1, 3, 8, 5.5], |
|
[4, 1, 6, 8.0], |
|
[5, 0, 5, 9.0], |
|
[6, 0, 6, 9.5] |
|
] |
|
|
|
|
|
X = torch.tensor([row[:3] for row in data], dtype=torch.float32) |
|
y = torch.tensor([[row[3]] for row in data], dtype=torch.float32) |
|
|
|
|
|
class StudentGradeModel(nn.Module): |
|
def __init__(self): |
|
super(StudentGradeModel, self).__init__() |
|
self.linear = nn.Linear(3, 1) |
|
|
|
def forward(self, x): |
|
return self.linear(x) |
|
|
|
model = StudentGradeModel() |
|
|
|
|
|
criterion = nn.MSELoss() |
|
optimizer = optim.SGD(model.parameters(), lr=0.01) |
|
|
|
|
|
for epoch in tqdm(range(10000), desc="Training Epochs"): |
|
optimizer.zero_grad() |
|
output = model(X) |
|
loss = criterion(output, y) |
|
loss.backward() |
|
optimizer.step() |
|
|
|
|
|
if (epoch + 1) % 1000 == 0: |
|
tqdm.write(f'Epoch [{epoch + 1}/10000], Loss: {loss.item():.4f}') |
|
|
|
|
|
model.eval() |
|
with torch.no_grad(): |
|
test_input = torch.tensor([[4, 1, 6]], dtype=torch.float32) |
|
prediction = model(test_input) |
|
print("Dự đoán điểm trung bình:", prediction.item()) |
|
|