-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_forest.py
More file actions
69 lines (56 loc) · 1.93 KB
/
random_forest.py
File metadata and controls
69 lines (56 loc) · 1.93 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
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
# Load dataset
df = pd.read_csv("dataset.csv")
# Split dataset into training and validation sets
train_texts, val_texts, train_labels, val_labels = train_test_split(
df["column_name"].tolist(),
df["is_hipaa_sensitive"].tolist(),
test_size=0.2,
random_state=42,
stratify=df["is_hipaa_sensitive"]
)
# Convert text into TF-IDF features
vectorizer = TfidfVectorizer(
ngram_range=(1, 2), # unigrams + bigrams
max_features=20000 # helps Random Forest performance
)
X_train = vectorizer.fit_transform(train_texts)
X_val = vectorizer.transform(val_texts)
# Train Random Forest model
rf = RandomForestClassifier(
n_estimators=500,
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
random_state=42,
n_jobs=-1,
class_weight="balanced" # important for HIPAA imbalance
)
rf.fit(X_train, train_labels)
# Make predictions
pred_labels = rf.predict(X_val)
# Calculate accuracy
accuracy = accuracy_score(val_labels, pred_labels)
print(f"Random Forest Accuracy: {accuracy * 100:.4f}%")
# Print classification report
print("\nClassification Report:\n",
classification_report(val_labels, pred_labels, target_names=["Non-Sensitive", "Sensitive"]))
# Function to test new examples
def predict_tf_idf(texts):
X_test = vectorizer.transform(texts)
predictions = rf.predict(X_test)
return ["Sensitive" if p == 1 else "Non-sensitive" for p in predictions]
# Test on new column names
test_texts = [
"birthDate", "birth_year", "country",
"DATE_BIRTH", "color", "food", "jwtToken"
]
predictions = predict_tf_idf(test_texts)
# Print predictions
print("\nPredictions:")
for text, pred in zip(test_texts, predictions):
print(f"{text}: {pred}")