コード例 #1
0
def cons_train_sample_for_cla(filename,indexes,dic_path,glo_aff_path,result_save_path,model_path,LSA_path,LSA_model_path,decom_meas,delete):
    dic_list = read_dic(dic_path,dtype=str)
    glo_aff_list = read_list(glo_aff_path)
    f= file(filename,'r')
    fs = file(result_save_path,'w')
    fd = file(dust_save_path,'w')
    m= svm_load_model(model_path)
    lsa_m = svm_load_model(LSA_model_path)
    U = load_lsa_model(LSA_path,"U")
    for line in f.readlines():
        text = line.strip().split(tc_splitTag)
        if len(text)!=line_length:
            fd.write(line)
            continue
        text_temp=""
        for i in indexes:
            text_temp+=str_splitTag+text[i]  
        vec = cons_vec_for_cla(text_temp.strip().split(str_splitTag),dic_list,glo_aff_list)
        y,x=cons_svm_problem(text[0],vec)
        p_lab,p_acc,p_sc=svm_predict(y,x,m)
 
        if  decom_meas==1:
            weight = cal_weight(p_sc[0][0])
            #vec = [value*weight for value in vec ] 
            vec = [0]*len(vec)
            for key in x[0].keys():
               vec[int(key)-1]= weight*float(x[0][key])    
            vec = pre_doc_svds(vec,U)
            y,x=cons_svm_problem(text[0],vec)
            lsa_lab,lsa_acc,lsa_sc = svm_predict(y,x,lsa_m)
            fs.write(text[0]+"\t"+str(p_sc[0][0])+"\t"+str(lsa_sc[0][0])+"\t"+text[1]+"\t"+text[2]+"\n")
        else :
            fs.write(text[0]+"\t"+str(p_sc[0][0])+"\t"+text[1]+"\t"+text[2]+"\n")
    f.close()
    fs.close()
コード例 #2
0
def ctm_feature_select(filename,indexes,global_fun,main_save_path,dic_name,ratio,stopword_filename,str_splitTag,tc_splitTag):
    #如果模型文件保存的路径不存在,则创建该文件夹
    dic_path= main_save_path+"model/"+dic_name
    if os.path.exists(main_save_path):
        if os.path.exists(main_save_path+"model/") is False:
            os.makedirs(main_save_path+"model/")
    #如果没有给出停用词的文件名,则默认不使用停用词
    if stopword_filename =="":
        stop_words_dic=dict()
    else:
        stop_words_dic = fileutil.read_dic(stopword_filename)
    feature_select(filename,indexes,global_fun,dic_path,ratio,stop_words_dic,str_splitTag,tc_splitTag)
コード例 #3
0
def ctm_train(filename, indexes, main_save_path, stopword_filename, svm_param,
              config_name, dic_name, model_name, train_name, svm_type,
              param_name, ratio, delete, str_splitTag, tc_splitTag, seg,
              param_select, global_fun, local_fun, label_file):
    '''训练的自动化程序,分词,先进行特征选择,重新定义词典,根据新的词典,自动选择SVM最优的参数。
    然后使用最优的参数进行SVM分类,最后生成训练后的模型。
    需要保存的文件:(需定义一个主保存路径)
                 模型文件:词典.key+模型.model
                临时文件 :svm分类数据文件.train
    filename 训练文本所在的文件名
    indexs需要训练的指标项
    main_save_path 模型保存的路径
    stopword_filename 停用词的名称以及路径 ;默认不适用停用词
    svm_type :svm类型:libsvm 或liblinear
    svm_param  用户自己设定的svm的参数,这个要区分libsvm与liblinear参数的限制;例如"-s 0 -t 2 -c 0.2 "
    dic_name 用户自定义词典名称;例如“dic.key”
    model_name用户自定义模型名称 ;例如"svm.model"
    train_name用户自定义训练样本名称 ;例如“svm.train”
    param_name用户自定义参数文件名称 ;例如"svm.param"
    ratio 特征选择保留词的比例 ;例如 0.4
    delete对于所有特征值为0的样本是否删除,True or False
    str_splitTag 分词所用的分割符号 例如"^"
    tc_splitTag训练样本中各个字段分割所用的符号 ,例如"\t"
    seg 分词的选择:0为不进行分词;1为使用mmseg分词;2为使用aliws分词
    param_select ;是否进行SVM模型参数的搜索。True即为使用SVM模型grid.搜索,False即为不使用参数搜索。
    local_fun:即对特征向量计算特征权重时需要设定的计算方式:x(i,j) = local(i,j)*global(i).可选的有tf,logtf
    global_fun :全局权重的计算方式:有"one","idf","rf"
    label_file:类标签的解释说明文件。
    '''

    print "-----------------创建模型文件保存的路径-----------------"
    if os.path.exists(main_save_path):
        if os.path.exists(os.path.join(main_save_path, "model")) is False:
            os.makedirs(os.path.join(main_save_path, "model"))
    if os.path.exists(main_save_path):
        if os.path.exists(os.path.join(main_save_path, "temp")) is False:
            os.makedirs(os.path.join(main_save_path, "temp"))

    #设定SVM模型的类型。

    tms_svm.set_svm_type(svm_type)

    #如果没有给出停用词的文件名,则默认不使用停用词
    if stopword_filename == "":
        stop_words_dic = dict()
    else:
        stop_words_dic = fileutil.read_dic(stopword_filename)

    #如果需要分词,则对原文件进行分词
    if seg != 0:
        print "-----------------正在对源文本进行分词-------------------"
        segment_file = os.path.dirname(filename) + "/segmented"
        segment.file_seg(filename, indexes, segment_file, str_splitTag,
                         tc_splitTag, seg)
        filename = segment_file

    #对原训练样本进行词干化处理
    print "-----------------正在对源文本进行词干化处理-------------------"
    stem.stemFile(filename, str_splitTag, tc_splitTag)

    print "-----------------现在正在进行特征选择---------------"
    dic_path = os.path.join(main_save_path, "model", dic_name)
    feature_select(filename,
                   indexes,
                   global_fun,
                   dic_path,
                   ratio,
                   stop_words_dic,
                   str_splitTag=str_splitTag,
                   tc_splitTag=tc_splitTag)

    print "-----------------再根据特征选择后的词典构造新的SVM分类所需的训练样本------------------- "
    problem_save_path = os.path.join(main_save_path, "temp", train_name)
    local_fun_str = local_fun
    local_fun = measure.local_f(local_fun)
    label = cons_train_sample_for_cla(filename, indexes, local_fun, dic_path,
                                      problem_save_path, delete, str_splitTag,
                                      tc_splitTag)

    if param_select == True:
        print "--------------------选择最优的c,g------------------------------"
        search_result_save_path = main_save_path + "temp/" + param_name
        if svm_type == "libsvm":
            coarse_c_range = (-5, 7, 2)
            coarse_g_range = (3, -10, -2)
            fine_c_step = 0.5
            fine_g_step = 0.5
            c, g = grid_search_param.grid(problem_save_path,
                                          search_result_save_path, svm_type,
                                          coarse_c_range, coarse_g_range,
                                          fine_c_step, fine_g_step)
            svm_param = svm_param + " -c " + str(c) + " -g " + str(g)
        if svm_type == "liblinear" or (svm_type == "libsvm" and
                                       is_linear_kernal(svm_param) is True):
            coarse_c_range = (-5, 7, 2)
            coarse_g_range = (1, 1, 1)
            fine_c_step = 0.5
            fine_g_step = 0
            c, g = grid_search_param.grid(problem_save_path,
                                          search_result_save_path, svm_type,
                                          coarse_c_range, coarse_g_range,
                                          fine_c_step, fine_g_step)
            svm_param = svm_param + " -c " + str(c)

    print "-----------------训练模型,并将模型进行保存----------"
    model_save_path = main_save_path + "model/" + model_name
    ctm_train_model(problem_save_path, svm_type, svm_param, model_save_path)

    print "-----------------保存模型配置-----------------"
    f_config = file(os.path.join(main_save_path, "model", config_name), 'w')
    save_config(f_config, dic_name, model_name, local_fun_str, global_fun, seg,
                svm_type, svm_param, label_file, label)
    f_config.close()
コード例 #4
0
def ctm_train(filename,indexes,main_save_path,stopword_filename,svm_param,config_name,dic_name,model_name,train_name,svm_type,param_name,ratio,delete,str_splitTag,tc_splitTag,seg,param_select,global_fun,local_fun,label_file):
    '''训练的自动化程序,分词,先进行特征选择,重新定义词典,根据新的词典,自动选择SVM最优的参数。
    然后使用最优的参数进行SVM分类,最后生成训练后的模型。
    需要保存的文件:(需定义一个主保存路径)
                 模型文件:词典.key+模型.model
                临时文件 :svm分类数据文件.train
    filename 训练文本所在的文件名
    indexs需要训练的指标项
    main_save_path 模型保存的路径
    stopword_filename 停用词的名称以及路径 ;默认不适用停用词
    svm_type :svm类型:libsvm 或liblinear
    svm_param  用户自己设定的svm的参数,这个要区分libsvm与liblinear参数的限制;例如"-s 0 -t 2 -c 0.2 "
    dic_name 用户自定义词典名称;例如“dic.key”
    model_name用户自定义模型名称 ;例如"svm.model"
    train_name用户自定义训练样本名称 ;例如“svm.train”
    param_name用户自定义参数文件名称 ;例如"svm.param"
    ratio 特征选择保留词的比例 ;例如 0.4
    delete对于所有特征值为0的样本是否删除,True or False
    str_splitTag 分词所用的分割符号 例如"^"
    tc_splitTag训练样本中各个字段分割所用的符号 ,例如"\t"
    seg 分词的选择:0为不进行分词;1为使用mmseg分词;2为使用aliws分词
    param_select ;是否进行SVM模型参数的搜索。True即为使用SVM模型grid.搜索,False即为不使用参数搜索。
    local_fun:即对特征向量计算特征权重时需要设定的计算方式:x(i,j) = local(i,j)*global(i).可选的有tf,logtf
    global_fun :全局权重的计算方式:有"one","idf","rf"
    label_file:类标签的解释说明文件。
    '''

    print "-----------------创建模型文件保存的路径-----------------"
    if os.path.exists(main_save_path):
        if os.path.exists(os.path.join(main_save_path,"model")) is False:
            os.makedirs(os.path.join(main_save_path,"model"))
    if os.path.exists(main_save_path):
        if os.path.exists(os.path.join(main_save_path,"temp")) is False:
            os.makedirs(os.path.join(main_save_path,"temp"))
    
    #设定SVM模型的类型。  
    
    tms_svm.set_svm_type(svm_type)   
        
    #如果没有给出停用词的文件名,则默认不使用停用词
    if stopword_filename =="":
        stop_words_dic=dict()
    else:
        stop_words_dic = fileutil.read_dic(stopword_filename)
    
    #如果需要分词,则对原文件进行分词
    if seg!=0:
        print "-----------------正在对源文本进行分词-------------------"
        segment_file = os.path.dirname(filename)+"/segmented"
        segment.file_seg(filename,indexes,segment_file,str_splitTag,tc_splitTag,seg)
        filename = segment_file
    
    #对原训练样本进行词干化处理
    print "-----------------正在对源文本进行词干化处理-------------------"
    stem.stemFile(filename,str_splitTag,tc_splitTag)
    
    print "-----------------现在正在进行特征选择---------------"  
    dic_path= os.path.join(main_save_path,"model",dic_name)    
    feature_select(filename,indexes,global_fun,dic_path,ratio,stop_words_dic,str_splitTag=str_splitTag,tc_splitTag=tc_splitTag)
    
    print "-----------------再根据特征选择后的词典构造新的SVM分类所需的训练样本------------------- "
    problem_save_path  = os.path.join(main_save_path,"temp",train_name)
    local_fun_str = local_fun
    local_fun = measure.local_f(local_fun)
    label = cons_train_sample_for_cla(filename,indexes,local_fun,dic_path,problem_save_path,delete,str_splitTag,tc_splitTag)
    
    if param_select ==True:
        print"--------------------选择最优的c,g------------------------------"
        search_result_save_path  = main_save_path +"temp/"+param_name
        if svm_type=="libsvm":
           coarse_c_range=(-5,7,2)
           coarse_g_range=(3,-10,-2)
           fine_c_step=0.5
           fine_g_step=0.5
           c,g=grid_search_param.grid(problem_save_path,search_result_save_path,svm_type,coarse_c_range,coarse_g_range,fine_c_step,fine_g_step)
           svm_param = svm_param + " -c "+str(c)+" -g "+str(g)
        if svm_type=="liblinear" or (svm_type=="libsvm" and is_linear_kernal(svm_param) is True):
           coarse_c_range=(-5,7,2)
           coarse_g_range=(1,1,1)
           fine_c_step=0.5
           fine_g_step=0
           c,g=grid_search_param.grid(problem_save_path,search_result_save_path,svm_type,coarse_c_range,coarse_g_range,fine_c_step,fine_g_step)
           svm_param = svm_param + " -c "+str(c)
    
    print "-----------------训练模型,并将模型进行保存----------"
    model_save_path  = main_save_path+"model/"+model_name
    ctm_train_model(problem_save_path,svm_type,svm_param,model_save_path)
    
    print "-----------------保存模型配置-----------------"
    f_config = file(os.path.join(main_save_path,"model",config_name),'w')
    save_config(f_config,dic_name,model_name,local_fun_str,global_fun,seg,svm_type,svm_param,label_file,label)
    f_config.close()