File size: 9,943 Bytes
020651d |
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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"# Sample Code for Training Binary Classroom Management Classification Measures\n",
"\n",
"This notebook provides sample code for training binary classification measures using the classroom management datasets included in the collection. It is intended as a minimal example for researchers.\n",
"\n",
"## Notes\n",
"This code uses the SimpleTransformers library, and the base model is RoBERTa. You can change the base model or experiment with hyperparameters here, though our paper [1] uses the defaults.\n",
"\n",
"\n",
"## How to Run\n",
"Download the \"classroom_management.csv\", \"behavior_management.csv\", or \"talkmoves.csv\" files in the collection and process so that you have two columns, \"text\" and \"labels\". Use this notebook for all columns *except for \"vs_submoves\" in the \"talkmoves.csv\" file, which is labeled for multiclass.\n",
"\n",
"## Author\n",
"Mei Tan, EduNLP Lab @ Stanford University Graduate School of Education, 2024\n",
"\n",
"[1] Tan, Mei, and Dorottya Demszky. (2025). Do As I Say: What Teachers’ Language Reveals About Classroom\n",
"Management Practices. (EdWorkingPaper: 23-844). Retrieved from Annenberg Institute at Brown University:\n",
"https://doi.org/10.26300/9yj6-jn52"
],
"metadata": {
"id": "Q-V-8f9-YiOw"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_e2V4GiAX_aO"
},
"outputs": [],
"source": [
"import pandas as pd\n",
"train_data = pd.read_csv(\"<YOUR PATH TO ONE DATA FILE HERE>\")"
]
},
{
"cell_type": "code",
"source": [
"!pip install --upgrade transformers\n",
"!pip install --upgrade simpletransformers\n",
"from simpletransformers.classification import ClassificationModel, ClassificationArgs\n",
"from sklearn.metrics import precision_score, recall_score, f1_score\n",
"from sklearn.model_selection import KFold, train_test_split\n",
"from scipy.stats import pearsonr, spearmanr\n",
"import warnings\n",
"import numpy as np\n",
"import pandas as pd\n",
"from sys import exit\n",
"import logging\n",
"import torch\n",
"import wandb\n",
"warnings.filterwarnings(\"ignore\")\n",
"transformers_logger = logging.getLogger(\"transformers\")\n",
"transformers_logger.setLevel(logging.WARNING)\n",
"\n",
"wandbproject = \"<ANY STRING TO NAME W AND B RUN HERE>\"\n",
"output_dir = \"<NAME YOUR OUTPUT FOLDER HERE>\""
],
"metadata": {
"id": "WgLR0PSIY3wO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def accuracy(preds, labels):\n",
" return sum([p == l for p, l in zip(preds, labels)]) /len(labels)\n",
"\n",
"def precision(preds, labels):\n",
" return precision_score(y_true=labels, y_pred=preds)\n",
"\n",
"def recall(preds, labels):\n",
" return recall_score(y_true=labels, y_pred=preds)\n",
"\n",
"def f1(preds, labels):\n",
" return f1_score(y_true=labels, y_pred=preds)"
],
"metadata": {
"id": "pDpbwBSCZMpP"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def train(label_name, label_col, text_col, train_df, eval_df, output_dir,\n",
" model=\"roberta\",\n",
" num_labels=2,\n",
" num_train_epochs=5,\n",
" train_batch_size=8,\n",
" gradient_accumulation_steps=2,\n",
" max_seq_length=512,\n",
" cross_validate=False,\n",
" balance_labels_oversample=False,\n",
" balance_labels_weights=False,\n",
" weights = None):\n",
"\n",
" if balance_labels_oversample:\n",
" most_common = train_df[label_col].value_counts().idxmax()\n",
" most_common_df = train_df[train_df[label_col]==most_common]\n",
" concat_list = [most_common_df]\n",
" for label, group in train_df[train_df[label_col]!=most_common].groupby(label_col):\n",
" concat_list.append(group.sample(replace=True, n=len(most_common_df)))\n",
" train_df = pd.concat(concat_list)\n",
"\n",
" train_df = train_df.sample(frac=1)\n",
" save_dir = output_dir + \"/\" + label_name + \"_train_size=\" + str(len(train_df))\n",
"\n",
" model_args = ClassificationArgs()\n",
" model_args.regression = num_labels == 1\n",
"\n",
" model_args.reprocess_input_data = True\n",
" model_args.overwrite_output_dir = True\n",
"\n",
" model_args.evaluate_during_training = True\n",
" model_args.evaluate_during_training_steps = int(len(train_df) / train_batch_size) # after each epoch\n",
" model_args.save_eval_checkpoints = False\n",
" model_args.save_model_every_epoch = False\n",
" model_args.no_save = cross_validate\n",
"\n",
" model_args.max_seq_length = int(max_seq_length / len(text_col))\n",
" model_args.num_train_epochs = num_train_epochs\n",
" model_args.train_batch_size = train_batch_size\n",
" model_args.gradient_accumulation_steps = gradient_accumulation_steps\n",
"\n",
" model_args.wandb_project = label_name\n",
" model_args.wandb_kwargs = {\"reinit\": True}\n",
"\n",
" model_args.output_dir = save_dir\n",
" model_args.best_model_dir = save_dir +\"/best_model\"\n",
" model_args.cache_dir = save_dir + \"/cache\"\n",
" model_args.tensorboard_dir = save_dir + \"/tensorboard\"\n",
" model_args.no_cache = False\n",
"\n",
" model_args.fp16 = False\n",
" model_args.fp16_opt_level = \"O0\"\n",
" model_args.save_optimizer_and_scheduler = True\n",
"\n",
" model_args.device = \"cuda:0\"\n",
"\n",
" if balance_labels_weights:\n",
" model = ClassificationModel(model.split(\"-\")[0], model,\n",
" use_cuda=True,\n",
" num_labels=num_labels,\n",
" args=model_args, weight=weights)\n",
" else:\n",
" model = ClassificationModel(model.split(\"-\")[0], model,\n",
" use_cuda=True,\n",
" num_labels=num_labels,\n",
" args=model_args)\n",
"\n",
" train_args = {\"use_multiprocessing\": False,\n",
" \"process_count\": 1,\n",
" \"use_multiprocessing_for_evaluation\": False}\n",
" if wandb.run is not None:\n",
" wandb.finish()\n",
" model.train_model(train_df,\n",
" eval_df=eval_df,\n",
" accuracy=accuracy,\n",
" precision=precision,\n",
" recall=recall,\n",
" f1=f1,\n",
" args=train_args)\n",
" return model"
],
"metadata": {
"id": "vH0GEpQLZOQd"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def predict(fname, model_path, model=None,\n",
" model_type=\"roberta-base\", predict_list=None,\n",
" index_list=None, index_colname=\"index\"):\n",
"\n",
" preds, outputs = model.predict(predict_list)\n",
" with open(model_path + '/' + fname + '_preds.txt', 'w') as f:\n",
" f.write(f\"{index_colname}\\tpred\\outputs\\n\")\n",
" for index, pred, output in zip(index_list, preds, outputs):\n",
" f.write(f\"{index}\\t{pred}\\t{output}\\n\")\n",
"\n",
" return preds"
],
"metadata": {
"id": "KdksfX6QZUKT"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Sample Train\n",
"model = train(wandbproject, \"labels\", \"text\", train_data, train_data, output_dir=output_dir,\n",
" model=\"roberta-base\", num_labels=2, balance_labels_oversample=True, balance_labels_weights=False, weights = None)"
],
"metadata": {
"id": "TLdaRVmWC5wm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Sample Predict\n",
"predict_data = pd.read_csv(\"<YOUR DATA PATH HERE>\")\n",
"predict_list = predict_data['text'].tolist()\n",
"index_list = predict_data['index'].tolist()\n",
"predict(wandbproject, \"predictions\", model, model_type=\"roberta-base\", predict_list=predict_list,\n",
" index_list=index_list, index_colname=\"index\")"
],
"metadata": {
"id": "apCjeYODDD0x"
},
"execution_count": null,
"outputs": []
}
]
} |