A Doc2Vec-based neural network model for classifying English text by CEFR (Common European Framework of Reference for Languages) proficiency levels.
This model is part of an ensemble CEFR text classification system that combines multiple approaches to estimate language proficiency levels.
The Doc2Vec classifier uses document embeddings fed into a fully connected neural network to capture semantic patterns characteristic of different proficiency levels.
1from huggingface_hub import snapshot_download
2from gensim.models import Doc2Vec
3import torch
4import torch.nn as nn
5import numpy as np
6import json
7import os
8
9# Download model files
10local_dir = "./doc2vec_model"
11snapshot_download(
12 repo_id="theluantran/cefr-doc2vec",
13 local_dir=local_dir,
14 local_dir_use_symlinks=False,
15 allow_patterns=[
16 "doc2vec_model*",
17 "*.json",
18 "nn_weights.pth"
19 ]
20)
21
22# Define neural network architecture
23class Doc2VecClassifier(nn.Module):
24 def __init__(self, embedding_dim, hidden_dim, num_classes, dropout=0.3):
25 super(Doc2VecClassifier, self).__init__()
26 self.fc1 = nn.Linear(embedding_dim, hidden_dim)
27 self.relu = nn.ReLU()
28 self.dropout = nn.Dropout(dropout)
29 self.fc2 = nn.Linear(hidden_dim, num_classes)
30
31 def forward(self, x):
32 x = self.fc1(x)
33 x = self.relu(x)
34 x = self.dropout(x)
35 x = self.fc2(x)
36 return x
37
38# Load Doc2Vec model
39doc2vec_model = Doc2Vec.load(os.path.join(local_dir, "doc2vec_model.bin"))
40
41# Load configuration
42with open(os.path.join(local_dir, "config.json"), 'r') as f:
43 config = json.load(f)
44
45# Reconstruct and load neural network
46neural_network = Doc2VecClassifier(
47 embedding_dim=config['embedding_dim'],
48 hidden_dim=config['hidden_dim'],
49 num_classes=config['num_classes'],
50 dropout=config['dropout_rate']
51)
52neural_network.load_state_dict(
53 torch.load(os.path.join(local_dir, "nn_weights.pth"))
54)
55neural_network.eval()
56
57# Predict
58text = "This is a sample text to classify"
59vector = doc2vec_model.infer_vector(text.split())
60
61with torch.no_grad():
62 tensor = torch.FloatTensor(vector).unsqueeze(0)
63 output = neural_network(tensor)
64 probabilities = torch.softmax(output, dim=1)
65
66probs_array = probabilities.numpy()[0]
67prediction = int(np.argmax(probs_array))
68
69# Map numeric prediction to CEFR level
70level_map = {0: 'A1', 1: 'A2', 2: 'B1', 3: 'B2', 4: 'C1/C2'}
71predicted_level = level_map[prediction]
72
73print(f"Predicted level: {predicted_level}")
74print(f"Confidence: {max(probs_array):.2%}")
75print(f"All probabilities: {dict(zip(level_map.values(), probs_array))}")
1{
2 "embedding_dim": 100,
3 "hidden_dim": 128,
4 "num_classes": 5,
5 "dropout_rate": 0.3
6}
This model was trained using proprietary CEFR-labeled text data. The training process involves:
This model is released for research and educational purposes. The training data is proprietary and not included.