minBERT / zemo1.py
GlowCheese's picture
First model version
9756d99
raw
history blame
1.91 kB
import torch
import torch.nn as nn
from tqdm import tqdm
import torch.optim as optim
# Bước 1: Chuẩn bị dữ liệu mẫu
# Dữ liệu giả: mỗi dòng là [giờ học, giờ giải trí, giờ ngủ], điểm trung bình
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]
]
# Tách đặc trưng (features) và mục tiêu (target)
X = torch.tensor([row[:3] for row in data], dtype=torch.float32) # Giờ học, giờ giải trí, giờ ngủ
y = torch.tensor([[row[3]] for row in data], dtype=torch.float32) # Điểm trung bình
# Bước 2: Xây dựng mô hình
class StudentGradeModel(nn.Module):
def __init__(self):
super(StudentGradeModel, self).__init__()
self.linear = nn.Linear(3, 1) # 3 đầu vào, 1 đầu ra
def forward(self, x):
return self.linear(x)
model = StudentGradeModel()
# Bước 3: Định nghĩa hàm mất mát và bộ tối ưu
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Bước 4: Huấn luyện mô hình
for epoch in tqdm(range(10000), desc="Training Epochs"):
optimizer.zero_grad() # Xóa gradient cũ
output = model(X) # Truyền dữ liệu qua mô hình
loss = criterion(output, y) # Tính mất mát
loss.backward() # Tính gradient
optimizer.step() # Cập nhật trọng số
# In loss để theo dõi quá trình huấn luyện
if (epoch + 1) % 1000 == 0:
tqdm.write(f'Epoch [{epoch + 1}/10000], Loss: {loss.item():.4f}')
# Bước 5: Dự đoán thử với một học sinh mới
model.eval()
with torch.no_grad():
test_input = torch.tensor([[4, 1, 6]], dtype=torch.float32) # Ví dụ: 4 giờ học, 1 giờ giải trí, 6 giờ ngủ
prediction = model(test_input)
print("Dự đoán điểm trung bình:", prediction.item())