def Test(model_name): dataset = 'C:/Users/USER/Documents/Capstone_Project/datalogs' # 数据集 p = os.path.dirname(os.path.dirname((os.path.abspath(__file__)))) if p not in sys.path: sys.path.append(p) do_train = False do_test = True x = import_module('models.{}'.format(model_name)) config = x.Config(dataset) np.random.seed(156) torch.cuda.manual_seed_all(1024) torch.backends.cudnn.deterministic = True start_time = time.time() print('Loading data...') train_data, dev_data, test_data = build_dataset(config, do_train, do_test) if do_test: test_iter = build_iterator(test_data, config, do_dev=True) time_dif = get_time_dif(start_time) model = x.Seq2SeqModel(config).to(config.device) for p in model.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) if do_test: test(config, model, test_iter)
def Pred(model, config): print("Testing...") with open("../user_data/tmp_data/B_nli_256.txt") as f: test_nli = json.load(f) with open("../user_data/tmp_data/B_tnews_256.txt") as f: test_news = json.load(f) with open("../user_data/tmp_data/B_emotion_256.txt") as f: test_emotion = json.load(f) print(len(test_nli), len(test_news), len(test_emotion)) test_iter1 = build_iterator(test_nli, config) test_iter2 = build_iterator(test_news, config) test_iter3 = build_iterator(test_emotion, config) test(config, model, test_iter1, test_iter2, test_iter3) print("End..")
def chat(**kwargs): opt = Config() for k, v in kwargs.items(): #设置参数 setattr(opt, k, v) searcher, sos, eos, unknown, word2ix, ix2word = train_eval.test(opt) if os.path.isfile(opt.corpus_data_path) == False: preprocess() while (1): input_sentence = input('BuaaSoft > ') if input_sentence == 'q' or input_sentence == 'quit' or input_sentence == 'exit': break if opt.use_QA_first: query_res = QA_test.match(input_sentence) if (query_res == tuple()): output_words = train_eval.output_answer( input_sentence, searcher, sos, eos, unknown, opt, word2ix, ix2word) else: output_words = "您是不是要找以下问题: " + query_res[ 1] + ',您可以尝试这样: ' + query_res[2] else: output_words = train_eval.output_answer(input_sentence, searcher, sos, eos, unknown, opt, word2ix, ix2word) print('BOT > ', output_words) QA_test.conn.close()
def reply(): opt = Config() # for k, v in kwargs.items(): #设置参数 # setattr(opt, k, v) searcher, sos, eos, unknown, word2ix, ix2word = train_eval.test(opt) if os.path.isfile(opt.corpus_data_path) == False: preprocess() input_sentence = request.form['msg'] #if input_sentence == 'q' or input_sentence == 'quit' or input_sentence == 'exit': break if opt.use_QA_first: query_res = QA_test.match(input_sentence) if (query_res == tuple()): output_words = train_eval.output_answer(input_sentence, searcher, sos, eos, unknown, opt, word2ix, ix2word) else: output_words = "您是不是要找以下问题: " + query_res[ 1] + ',您可以尝试这样: ' + query_res[2] else: output_words = train_eval.output_answer(input_sentence, searcher, sos, eos, unknown, opt, word2ix, ix2word) print('BOT > ', output_words) return jsonify({'text': output_words})
def chat(**kwargs): opt = Config() for k, v in kwargs.items(): #设置参数 setattr(opt, k, v) searcher, sos, eos, unknown, word2ix, ix2word = train_eval.test(opt) if os.path.isfile(opt.corpus_data_path) == False: preprocess() while(1): input_sentence = input('Doragd > ') if input_sentence == 'q' or input_sentence == 'quit' or input_sentence == 'exit': break output_words = train_eval.output_answer(input_sentence, searcher, sos, eos, unknown, opt, word2ix, ix2word) print('BOT > ',output_words)
torch.backends.cudnn.deterministic = True # 保证每次结果一样 config.test_path = dataset + '/unlabeled_data.csv' start_time = time.time() data_df = load_data(config.test_path, config, with_label=False) print('Reading testing data...') test_data = Mydataset(config=config, data=data_df, with_labels=False) test_iter = DataLoader(dataset=test_data, batch_size=config.batch_size, shuffle=False) time_dif = get_time_dif(start_time) print("Time usage:", time_dif) model = bert_RNN(config).to(config.device) predict_all = test(config, model, test_iter) # ---------------------生成文件-------------------------- df_test = pd.read_csv(config.submit_example_path, encoding='utf-8') id2label, label2id = json.load(open(config.id2label_path)) id2label = {int(i): j for i, j in id2label.items()} # 转为int型(原本是字符串形式) class_labels = [] rank_labels = [] for i in predict_all: label = str(id2label[i]) class_labels.append(label) if label in ['财经', '时政']: rank_label = str('高风险') elif label in ['房产', '科技']: rank_label = str('中风险') elif label in ['教育', '时尚', '游戏']:
pretrained_dict = torch.load(config.load_path) # 1. filter out unnecessary keys premodel_dict = { k: v for k, v in pretrained_dict.items() if k != 'fc.weight' } premodel_dict = { k: v for k, v in premodel_dict.items() if k != 'fc.bias' } # 2. overwrite entries in the existing state dict pre_model.load_state_dict(premodel_dict, strict=False) # 加载模型权重,strick=False表示不加载无效层 print(pre_model.parameters) if args.start == 'train': train(config, pre_model, train_iter, dev_iter, test_iter) elif args.start == 'test': test(config, pre_model, test_iter) os._exit(1) model = x.Model(config).to(config.device) if model_name != 'Transformer': init_network(model) print(model.parameters) if args.start == 'train': train(config, model, train_iter, dev_iter, test_iter) elif args.start == 'test': test(config, model, test_iter)
dev_iter = build_iterator(dev_data, config) test_iter = build_iterator(test_data, config) test_set.append(test_iter) time_dif = get_time_dif(start_time) print("Time usage:", time_dif) # train config.n_vocab = len(vocab) model = x.Model(config).to(config.device) if model_name != 'Transformer': init_network(model) print(model.parameters) # 在测试BWT的时候,我们将学习完之前任务的模型继续在新任务上训练,因此训练之前会直接读取上一次训练完成的ckpt。 # 在学习第一个任务的时候不需要这个操作,因此在domain-0的时候删除之前训练遗留的模型文件。 if domain == 0 and os.path.exists(config.save_path): os.remove(config.save_path) model = train(config, model, train_iter, dev_iter, test_iter) for it in range(domain + 1): _acc, _f1 = test(config, model, test_set[it]) sheet1.write(domain + 3, it + 1, _acc) acc.append(_acc) f1.append(_f1) xls.save('JD21/result/' + args.model + args.domMode + str(args.domNum) + 'BWT.xls')
# start_time = time.time() # print("Loading data...") # train_data, dev_data, test_data = build_dataset(config) # train_iter = build_iterator(train_data, config) # dev_iter = build_iterator(dev_data, config) # test_iter = build_iterator(test_data, config) # time_dif = get_time_dif(start_time) # print("Time usage:", time_dif) # train for i in range(3,5): config.train_path = dataset + '/data/fold5/cvfold'+str(i)+'_train.txt' config.dev_path = dataset + '/data/fold5/cvfold'+str(i)+'_dev.txt' config.test_path = dataset + '/data/fold5/cv_valid.txt' config.save_path = dataset + '/saved_dict/' + config.model_name + '512-5fold-'+str(i)+'.bin' #if i==0 or i==1: # config.num_epochs = 1 submit_data = build_dataset(config) #train_iter = build_iterator(train_data, config) #dev_iter = build_iterator(dev_data, config) #test_iter = build_iterator(test_data, config) submit_iter = build_iterator(submit_data, config) model = x.Model(config).to(config.device) test(config, model, submit_iter, 'bertdrop_submitb_'+str(i)+'.npy') #test(config, model, test_iter,'bertRNN_valid_'+str(i)+'.npy') #test(config, model, dev_iter, 'bertRNN_train_'+str(i)+'.npy') #model.load_state_dict(torch.load(config.save_path)) #train(config, model, train_iter, dev_iter, test_iter)
## 测试单条句子 sentence="哈哈哈哈你好啊啊" sentence="""鲍勃库西奖归谁属? NCAA最强控卫是坎巴还是弗神新浪体育讯如今,本赛季的NCAA进入到了末段,各项奖项的评选结果也即将出炉, 其中评选最佳控卫的鲍勃-库西奖就将在下周最终四强战时公布,鲍勃-库西奖是由奈史密斯篮球名人堂提供,旨在奖励年度最佳大学控 卫。最终获奖的球员也即将在以下几名热门人选中产生。〈〈〈 NCAA疯狂三月专题主页上线,点击链接查看精彩内容吉梅尔-弗雷戴特 ,杨百翰大学“弗神”吉梅尔-弗雷戴特一直都备受关注,他不仅仅是一名射手,他会用“终结对手脚踝”一样的变向过掉面前的防守>者,并且他可以用任意一支手完成得分,如果他被犯规了,可以提前把这两份划入他的帐下了,因为他是一名命中率高达90%的罚球手>。弗雷戴特具有所有伟大控卫都具备的一点特质,他是一位赢家也是一位领导者。“他整个赛季至始至终的稳定领导着球队前进,这是 无可比拟的。”杨百翰大学主教练戴夫-罗斯称赞道,“他的得分能力毋庸置疑,但是我认为他带领球队获胜的能力才是他最重要的控>卫职责。我们在主场之外的比赛(客场或中立场)共取胜19场,他都表现的很棒。”弗雷戴特能否在NBA取得成功?当然,但是有很多专>业人士比我们更有资格去做出这样的判断。“我喜爱他。”凯尔特人主教练多克-里弗斯说道,“他很棒,我看过ESPN的片段剪辑,从>剪辑来看,他是个超级巨星,我认为他很成为一名优秀的NBA球员。”诺兰-史密斯,杜克大学当赛季初,球队宣布大一天才控卫凯瑞->厄尔文因脚趾的伤病缺席赛季大部分比赛后,诺兰-史密斯便开始接管球权,他在进攻端上足发条,在ACC联盟(杜克大学所在分区)的得 分榜上名列前茅,但同时他在分区助攻榜上也占据头名,这在众强林立的ACC联盟前无古人。“我不认为全美有其他的球员能在凯瑞-厄 尔文受伤后,如此好的接管球队,并且之前毫无准备。”杜克主教练迈克-沙舍夫斯基赞扬道,“他会将比赛带入自己的节奏,得分,>组织,领导球队,无所不能。而且他现在是攻防俱佳,对持球人的防守很有提高。总之他拥有了辉煌的赛季。”坎巴-沃克,康涅狄格>大学坎巴-沃克带领康涅狄格在赛季初的毛伊岛邀请赛一路力克密歇根州大和肯塔基等队夺冠,他场均30分4助攻得到最佳球员。在大东 赛区锦标赛和全国锦标赛中,他场均27.1分,6.1个篮板,5.1次助攻,依旧如此给力。他以疯狂的表现开始这个赛季,也将以疯狂的表 现结束这个赛季。“我们在全国锦标赛中前进着,并且之前曾经5天连赢5场,赢得了大东赛区锦标赛的冠军,这些都归功于坎巴-沃克>。”康涅狄格大学主教练吉姆-卡洪称赞道,“他是一名纯正的控卫而且能为我们得分,他有过单场42分,有过单场17助攻,也有过单>场15篮板。这些都是一名6英尺175镑的球员所完成的啊!我们有很多好球员,但他才是最好的领导者,为球队所做的贡献也是最大。” 乔丹-泰勒,威斯康辛大学全美没有一个持球者能像乔丹-泰勒一样很少失误,他4.26的助攻失误在全美遥遥领先,在大十赛区的比赛中 ,他平均35.8分钟才会有一次失误。他还是名很出色的得分手,全场砍下39分击败印第安纳大学的比赛就是最好的证明,其中下半场他 曾经连拿18分。“那个夜晚他证明自己值得首轮顺位。”当时的见证者印第安纳大学主教练汤姆-克雷恩说道。“对一名控卫的所有要>求不过是领导球队、使球队变的更好、带领球队成功,乔丹-泰勒全做到了。”威斯康辛教练博-莱恩说道""" print(sentence) res= test(config, model,TEXT,sentence) print(res) sentence="""景顺长城就参与新股询价问题作出说明⊙本报记者 黄金滔 安仲文 景顺长城基金管理有限公司11日在其网站上就参与新股询价有关问 题作出说明,表示该公司本着独立、客观、诚信的原则参与新股询价,遵守相关法律法规和公司内部制度,并切实保障了基金持有人利 益,并表示将严肃对待中国证券业协会对其提出的自律处理。景顺长城表示,作为中国证券业协会认定的IPO询价对象,该公司认真履>行询价义务,2008年度共参与7只新股询价。根据该公司报价区间和实际发行价格的比较,不存在较大价格偏离现象及操纵价格嫌疑。>对于公司参与询价的股票,除其中1只股票由于公司旗下基金参与了同一发行期内另外5只股票网上申购而没有申购外,其余6只股票全>部参与网上申购。据了解,根据《关于基金投资非公开发行股票等流通受限证券有关问题的通知》(证监基金字[2006]141号),为了>切实保护基金持有人利益、防范基金资产的流动性风险,景顺长城公司于2006年7月修改投资管理制度,明确规定“不投资带有锁定期>的证券”,因此,从2006年8月起,该公司没有投资任何带有锁定期的股票,包括IPO网下申购;并且在每次参与新股询价时,公司在递 交的《新股询价信息表》中的“在报价区间的申购意向”一栏均明确填写“不确定”或“不申购”。不过,景顺长城也强调,由于中国 证券市场处于快速发展时期,法规制度不断完善,该公司将严肃对待中国证券业协会对其提出的自律处理,一如既往地以审慎诚信的态 度为投资人服务""" res=test(config, model , TEXT, sentence) print(res)
# 构建数据迭代器 train_loader = build_iterator('train', device, config, feat_cols, is_wide, is_mask) dev_loader = build_iterator('dev', device, config, feat_cols, is_wide, is_mask) model = Model(config, embedding_pretraineds, device) # 定义模型 print(model) train(config, model, train_loader, dev_loader) test_loader = build_iterator('test', device, config, feat_cols, is_wide, is_mask) preds_age = test(config, model, test_loader) index_col = config.getint('model_parameters_settings', 'test_index') # 生成提交数据 df_test = pd.read_hdf( config['model_parameters_settings']['path_model_test']) preds_age = preds_age + 1 preds_gender = [4] * len(preds_age) df_submit = pd.DataFrame({ 'user_id': df_test[128], 'predicted_age': preds_age, 'predicted_gender': preds_gender }) df_submit = df_submit[['user_id', 'predicted_age', 'predicted_gender']]
if args.type == 'train': start_time = time.time() print("Loading data...") vocab, train_data, dev_data, test_data = build_dataset(config, args.type) train_iter = build_iterator(train_data, config) dev_iter = build_iterator(dev_data, config) test_iter = build_iterator(test_data, config) time_dif = get_time_dif(start_time) print("Time usage:", time_dif) # train config.n_vocab = len(vocab) model = x.Model(config).to(config.device) init_network(model) print(model.parameters) train(config, model, train_iter, dev_iter, test_iter) test(config, model, test_iter, args.type) if args.type == 'test': from data_pre import test_data_pre start_time = time.time() config.test_path = path.user_test_pre_path # Preprocessed data test_data_pre(args.file, config.test_path) vocab, test_data = build_dataset(config, args.type) test_iter = build_iterator(test_data, config) config.n_vocab = len(vocab) model = x.Model(config).to(config.device) init_network(model) print(model.parameters) test(config, model, test_iter, args.type)