File size: 9,570 Bytes
77f31ea | 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | import os
import pandas as pd
import shutil
from random import shuffle
import argparse
import json
DATA_DIR = "./data"
DATASET_PRE_DIR = "./predata"
DATASET_DIR = "./final"
CHUNKSIZE = 10000
def generate_pre_dataset_src(course):
"""
Generate an ASSIST-like data set that can be used by the PRE model, remove the test questions with a score of 0, and do not divide and label the data set
"""
print(f"generate sourse dataset of course {course}")
# create folders for course-related information
course_dir = DATASET_PRE_DIR + f"{course}"
if not os.path.exists(course_dir):
os.mkdir(course_dir)
print(f"make dir {course_dir}")
submission_csv = DATA_DIR+f"{course}/response_log.csv"
# output files
dataset_csv = course_dir + "/dataset.csv"
q_csv = course_dir + "/q.csv"
# read knowledge concept information related files
problem_knowledge_json = DATA_DIR+f"problem_knowledge.json"
psp_full_score_json = DATA_DIR+f"psp_full_score.json"
psp_problem_json = DATA_DIR+f"psp_problem.json"
# read json dict
with open(problem_knowledge_json,'r') as f:
knowledge_dict = json.load(f)
with open(psp_full_score_json,'r') as f:
full_score_dict = json.load(f)
with open(psp_problem_json,'r') as f:
problem_dict = json.load(f)
q_matrix = {}
# generate response logs
df_chunk = pd.read_csv(submission_csv, dtype=object, chunksize=CHUNKSIZE)
total = 0
drop = 0
for chunk in df_chunk:
content = []
for index, row in chunk.iterrows():
total += 1
user_id = row["user_id"]
psp_id = row["problem_set_problem_id"]
p_id = problem_dict[psp_id]
submission_id = row["submission_id"]
# calculating scoring rate
final_score = 0
status = row["status"]
score = float(row["score"])
full_score = float(full_score_dict[psp_id])
if status == "ACCEPTED":
final_score = 1
elif status == "WRONG_ANSWER":
final_score = 0
else:
if full_score == 0:
if float(score) == 0:
pass
else:
drop+=1
print(f"problem_set_problem_id/submission_id: {psp_id}/{submission_id}")
continue
else:
final_score = float(score)/float(full_score)
# Q-matrix
if p_id not in q_matrix.keys():
knowledge_id = knowledge_dict[p_id]
q_matrix[p_id] = knowledge_id
row = [user_id, p_id, final_score]
content.append(row)
# write problem info
df = pd.DataFrame(content,
columns=["user_id", "problem_id", "score"])
flag = True
if os.path.exists(dataset_csv):
flag = False
df.to_csv(dataset_csv, mode='a', index=False, header=flag)
print(f"till this chunk drop/total: {drop}/{total}")
# generate Q-matrix
content = []
for i in q_matrix.keys():
row = [i, q_matrix[i]]
content.append(row)
df = pd.DataFrame(content, columns=["item_id", "knowledge_code"])
df.to_csv(q_csv, index=False)
print(f"generate dataset in {dataset_csv}, q_matrix in {q_csv} with {len(content)} items")
def generate_final_dataset_with_index(course):
"""
Convert the data set of non-indexed values into indexed ones, and output them into the final data set
"""
print(f"generate final dataset with index of course {course}")
# file paths
dir_path = DATASET_DIR + f'{course}'
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# output files
dst_dataset_path = dir_path + "/dataset.csv"
dst_info_path = dir_path + "/info.json"
# data source file
dataset_file = DATASET_PRE_DIR + f"{course}/dataset.csv"
info_dir = DATASET_PRE_DIR + f"{course}/info/"
info_path = info_dir+"info.json"
problem_list_file = info_dir+"problem_list.txt"
student_list_file = info_dir+"student_list.txt"
# read files
with open(student_list_file, "r") as f:
data = f.read()
student_list = data.strip("\n").split(", ")
with open(problem_list_file, "r") as f:
data = f.read()
problem_list = data.strip("\n").split(", ")
dataset_data = pd.read_csv(dataset_file, dtype=object)
# index mapping
# replace item_id in dataset
for i, e in enumerate(problem_list):
dataset_data["problem_id"].replace(e, problem_list.index(e), inplace=True)
if i % 100 == 0:
print(f"replace item_id {i}/{len(problem_list)}")
print(f"replace item_id({len(problem_list)}) in dataset")
# replace user_id in dataset
for i, e in enumerate(student_list):
dataset_data["user_id"].replace(e, student_list.index(e), inplace=True)
if i % 100 == 0:
print(f"replace user_id {i}/{len(student_list)}")
print(f"replace user_id({len(student_list)}) in dataset")
dataset_data = dataset_data.rename(columns={"problem_id":"item_id"})
dataset_data.to_csv(dst_dataset_path, index=False)
shutil.copyfile(info_path, dst_info_path)
print(f"save files in {dir_path}")
def generate_final_item_with_index(course):
"""
Convert the q matrix of non-indexed values into indexed ones, and output them to the final data set
"""
print(f"generate final q-matrix with index of course {course}")
# file paths
dir_path = DATASET_DIR + f'{course}'
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# output files
dst_item_path = dir_path + "/item.csv"
# info files
info_dir = DATASET_PRE_DIR + f"{course}/info/"
concept_list_file = info_dir+"concept_list.txt"
problem_list_file = info_dir+"problem_list.txt"
item_csv = DATASET_PRE_DIR + f"{course}/q.csv"
# read files
with open(concept_list_file, "r") as f:
data = f.read()
concept_list = data.strip("\n").split(", ")
with open(problem_list_file, "r") as f:
data = f.read()
problem_list = data.strip("\n").split(", ")
item_data = pd.read_csv(item_csv, dtype=object)
# index mapping
# replace knowledge_id in dataset
for i in range(len(item_data)):
knowledges = item_data.iloc[i]["knowledge_code"].strip("[").strip("]").split(", ")
res = []
for j in knowledges:
j = j.strip("\'")
res.append(concept_list.index(j))
item_data.iloc[i]["knowledge_code"] = res
# replace knowledge_id in q-matrix
for i, e in enumerate(problem_list):
item_data["item_id"].replace(e, problem_list.index(e), inplace=True)
if i % 100 == 0:
print(f"replace item_id {i}/{len(problem_list)}")
print(f"replace item_id({len(problem_list)}) in q-matrix")
item_data.to_csv(dst_item_path, index=False)
print(f"save files in {dir_path}")
def split_dataset_src(course):
"""
Split the dataset by train/valid/test set 7:1:2
"""
print(f"split dataset of course {course}")
# data source
dataset_file = DATASET_DIR + f"{course}/dataset.csv"
# output files
train_file = DATASET_DIR + f"{course}/train.csv"
test_file = DATASET_DIR + f"{course}/test.csv"
valid_file = DATASET_DIR + f"{course}/valid.csv"
# create new csv
for i in [train_file, test_file, valid_file]:
if not os.path.exists(i):
content = []
df = pd.DataFrame(content, columns=['user_id', 'item_id','score'])
df.to_csv(i, index=False)
dataset_df = pd.read_csv(dataset_file)
user_group = dataset_df.groupby(["user_id"])
indices = user_group.indices
train_cnt = 0
test_cnt = 0
valid_cnt = 0
cnt = 0
total = len(user_group.groups)
for group in user_group.groups:
cnt += 1
index_list = indices[group]
length = len(index_list)
shuffle(index_list)
# split data
if cnt%2==0:
train = index_list[:int(7*length/10)+1]
test = index_list[int(4*length/5)+1:]
valid = index_list[int(7*length/10)+1:int(4*length/5)+1]
else:
train = index_list[:int(7*length/10)]
test = index_list[int(4*length/5):]
valid = index_list[int(7*length/10):int(4*length/5)]
train_cnt += len(train)
test_cnt += len(test)
valid_cnt += len(valid)
# write according files
train_df = dataset_df.iloc[train]
train_df.to_csv(train_file, mode='a', header=False, index=False)
test_df = dataset_df.iloc[test]
test_df.to_csv(test_file, mode='a', header=False, index=False)
valid_df = dataset_df.iloc[valid]
valid_df.to_csv(valid_file, mode='a', header=False, index=False)
print(f"for user {group} train/valid/test count: {len(train)}/{len(valid)}/{len(test)}")
if cnt % 100 ==0:
print(f"student cnt/total: {cnt}/{total}")
print(f"for {course} train/valid/test count: {train_cnt}/{valid_cnt}/{test_cnt}")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--course', '-c', type=str, default="Java_programming")
args = parser.parse_args()
course = args.course
generate_pre_dataset_src(course)
generate_final_dataset_with_index(course)
generate_final_item_with_index(course)
split_dataset_src(course) |