Download scripts/index_mapping_for_CD.py from whning0513/PTADisc: direct link, hf CLI and curl.
- Browser
- Download file 9.57 kB
-
https://huggingface.co/datasets/whning0513/PTADisc/resolve/main/scripts/index_mapping_for_CD.py
- Command line
-
hf download hf://datasets/whning0513/PTADisc/scripts/index_mapping_for_CD.py
-
curl -L -o index_mapping_for_CD.py https://huggingface.co/datasets/whning0513/PTADisc/resolve/main/scripts/index_mapping_for_CD.py
9.57 kB
| 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) |