-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbert_train.py
More file actions
147 lines (98 loc) · 4.29 KB
/
bert_train.py
File metadata and controls
147 lines (98 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import math
import random
import numpy as np
import toml
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from utils.dataset import CensusDataset
from utils.models import TableBERT, TabTransformer
def cus_scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False):
scale = 1.0 / math.sqrt(query.size(-1))
attn_weights = torch.matmul(query, key.transpose(-2, -1)) * scale
if attn_mask is not None:
attn_weights += attn_mask
attn_weights = torch.softmax(attn_weights, dim=-1)
if dropout_p > 0.0:
attn_weights = torch.nn.functional.dropout(
attn_weights, p=dropout_p)
output = torch.matmul(attn_weights, value)
return output
from contextlib import contextmanager
@contextmanager
def use_cus_scaled_dot_product_attention():
original_sdp_attention = torch.nn.functional.scaled_dot_product_attention
try:
torch.nn.functional.scaled_dot_product_attention = cus_scaled_dot_product_attention
yield
finally:
torch.nn.functional.scaled_dot_product_attention = original_sdp_attention
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
def preprocess_compas():
df = pd.read_csv('./dataset/compas/compas-scores-two-years.csv')
features = ['age', 'sex', 'race', 'priors_count', 'c_charge_degree',
'juv_fel_count', 'juv_misd_count', 'juv_other_count']
df = df[(df.days_b_screening_arrest <= 30) &
(df.days_b_screening_arrest >= -30) &
(df.is_recid != -1) &
(df.c_charge_degree != 'O') &
(df.score_text != 'N/A')]
le = LabelEncoder()
df['sex'] = le.fit_transform(df['sex'])
df['race'] = le.fit_transform(df['race'])
df['c_charge_degree'] = le.fit_transform(df['c_charge_degree'])
X = df[features]
y = df['two_year_recid']
protected = df['race']
scaler = StandardScaler()
numerical_features = ['age', 'priors_count', 'juv_fel_count',
'juv_misd_count', 'juv_other_count']
X[numerical_features] = scaler.fit_transform(X[numerical_features])
X_train, X_test, y_train, y_test, p_train, p_test = train_test_split(
X, y, protected, test_size=0.3, random_state=42)
return X_train, X_test, y_train, y_test, p_train, p_test
X_train, X_test, y_train, y_test, p_train, p_test = preprocess_compas()
X_train = X_train.to_numpy()
X_test = X_test.to_numpy()
Y_train = y_train.to_numpy()
Y_test = y_test.to_numpy()
config = toml.load('./config/credit.toml')
train_dataset = CensusDataset(X_train, Y_train)
test_dataset = CensusDataset(X_test, Y_test)
train_loader = DataLoader(train_dataset, batch_size=config["train"]["batch_size"], shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=config["train"]["batch_size"], shuffle=False)
device = "cuda"
model = TableBERT(**config["model"]).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=config["train"]["lr"], weight_decay=config["train"]["weight_decay"])
for epoch in range(config["train"]["num_epochs"]):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print(f"Epoch {epoch} loss: {loss.item()}")
model.eval()
test_loss = 0
correct = 0
total = 0
with use_cus_scaled_dot_product_attention():
for batch_idx, (data, target) in enumerate(test_loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
test_loss += loss.item()
_, predicted = output.max(1)
total += target.size(0)
correct += predicted.eq(target).sum().item()
test_loss /= len(test_loader.dataset)
test_accuracy = 100. * correct / total
print(f"Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.2f}%")
torch.save(model.state_dict(), "./models/compas_model.pth")