-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_classifier.py
More file actions
36 lines (28 loc) · 1.21 KB
/
train_classifier.py
File metadata and controls
36 lines (28 loc) · 1.21 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
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
# Function to pad or truncate sequences to a fixed length
def pad_sequences(sequences, maxlen):
padded_sequences = np.zeros((len(sequences), maxlen))
for i, seq in enumerate(sequences):
if len(seq) > maxlen:
padded_sequences[i, :] = seq[:maxlen]
else:
padded_sequences[i, :len(seq)] = seq
return padded_sequences
data_dict = pickle.load(open('./data.pickle', 'rb'))
# Set the desired fixed length for all sequences
fixed_length = 100 # Adjust this value based on your data
data = pad_sequences(data_dict['data'], maxlen=fixed_length)
labels = np.asarray(data_dict['labels'])
x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, shuffle=True, stratify=labels)
model = RandomForestClassifier()
model.fit(x_train, y_train)
y_predict = model.predict(x_test)
score = accuracy_score(y_predict, y_test)
print('{}% of samples were classified correctly !'.format(score * 100))
f = open('model.p', 'wb')
pickle.dump({'model': model}, f)
f.close()