溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

tensorflow怎么配置

發(fā)布時間:2021-12-23 17:38:10 來源:億速云 閱讀:165 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“tensorflow怎么配置”,在日常操作中,相信很多人在tensorflow怎么配置問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”tensorflow怎么配置”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

1.訓練樣本文件轉換為集合
[]整個文件
[]每段話
[]分詞,tag

2.將IOB模式標簽轉換為IOBES/B 開頭,I 中間,E 結尾,S 單獨,O 其他
B- => S-
I- => E-

3.創(chuàng)建字符和ID映射關系

當pkl文件不存在時
1)創(chuàng)建字符和ID映射字典
提取chars(所有詞組)生成dico(詞組加詞頻)倒序排列后生成char_to_id,id_to_char
2)同理創(chuàng)建標簽和id的映射字典
提取tags(所有tag)生成dico(tag加頻率)倒序排列后生成tag_to_id,id_to_tag,且寫到tag_to_id.txt和id_to_tag.txt中
3)將映射關系存儲到pkl文件中
(將映射關系對象obj序列化保存到文件中)
char_to_id,id_to_char,tag_to_id,id_to_tag

當pkl文件存在時
反序列化映射關系對象,將文件中的數(shù)據(jù)解析為char_to_id,id_to_char,tag_to_id,id_to_tag

4.將樣本數(shù)據(jù)轉為 單字符、對應的id、對應的分詞轉為(123)、對應的標簽id 列表  train_data
data = []   data.append([string, chars, segs, tags])
string: 一段話中所有詞組的list
chars: string中每個詞在char_to_id字典中的id的list
segs:
    tmp = [2] * len(str(word))
    tmp[0] = 1
    tmp[-1] = 3
    seg_feature.extend(tmp)
    string通過segment分詞后的word_list遍歷word后得到的seg_feature(是個list:[0,0,0,1,2,3,1,2,2,2,3,0,0])
    
tags: string中每個tag在tag_to_id字典中的id的list

5.批量管理,將一批數(shù)據(jù)按批次大小拆分
train_manager: batch_data
               len_data
               
batch_data: list()  batch_data.append([strings, chars, segs, targets]) 

6.生成相關路徑,生成配置文件
result_path,ckpt_path,config_file

7.tensorflow配置
設置步長
加載緩存

創(chuàng)建空模型:
通過checkpoint文件查找模型文件名
tf.global_variables_initializer()添加節(jié)點用于初始化所有的全局變量(GraphKeys.VARIABLES)。
返回一個初始化所有全局變量的操作(op),在構建完整個模型并在會話中加載模型后,運行這個節(jié)點。

設置使用CPU/GPU
設置訓練次數(shù)
遍歷亂序train_manager后的batch進行模型訓練
step, batch_loss = model.run_step(sess, True, batch)
loss.append(batch_loss)

每20批次(步長steps_check)計算下剩余批次所需時間并打印日志(MSE表示了預測值與目標值之間差值
的平方和然后求平均 np.mean(loss)))

通過dev文件優(yōu)化模型并保存
evaluate(sess, model, "dev", dev_manager, id_to_tag)

def evaluate(sess, model, name, data, id_to_tag): #logger = None
    logger.info("evaluate:{}".format(name))
    ner_results = model.evaluate(sess, data, id_to_tag)
    eval_lines = test_ner(ner_results, FLAGS.result_path)
    message = 'eval_lines value:{}'.format(eval_lines)
    # print(message)
    logger.info(message)
    f1 = float(eval_lines[1].strip().split()[-1])

    if name == "dev":
        best_test_f1 = model.best_dev_f1.eval()
        if f1 > best_test_f1:
            tf.assign(model.best_dev_f1, f1).eval()
            # print("new best dev f1 score:{:>.3f}".format(f1))
            logger.info("new best dev f1 score:{:>.3f}".format(f1))
        return f1 > best_test_f1
    elif name == "test":
        best_test_f1 = model.best_test_f1.eval()
        if f1 > best_test_f1:
            tf.assign(model.best_test_f1, f1).eval()
            # print("new best test f1 score:{:>.3f}".format(f1))
            logger.info("new best test f1 score:{:>.3f}".format(f1))
        return f1 > best_test_f1

def evaluate(self, sess, data_manager, id_to_tag):
    results = []
    trans = self.trans.eval()
    for batch in data_manager.iter_batch():
        strings = batch[0]
        tags = batch[-1]
        lengths, scores = self.run_step(sess, False, batch)
        batch_paths = self.decode(scores, lengths, trans)
        for i in range(len(strings)):
            result = []
            string = strings[i][:lengths[i]]
            gold = iobes_iob([id_to_tag[int(x)] for x in tags[i][:lengths[i]]])
            pred = iobes_iob([id_to_tag[int(x)] for x in batch_paths[i][:lengths[i]]])
            # gold = iob_iobes([id_to_tag[int(x)] for x in tags[i][:lengths[i]]])
            # pred = iob_iobes([id_to_tag[int(x)] for x in batch_paths[i][:lengths[i]]])
            for char, gold, pred in zip(string, gold, pred):
                result.append(" ".join([char, gold, pred]))
            results.append(result)
    return results

def test_ner(results, path):
    output_file = os.path.join(path, "ner_predict.utf8")
    with open(output_file, "w",encoding='utf8') as f:
        to_write = []
        for block in results:
            for line in block:
                to_write.append(line + "\n")
            to_write.append("\n")

        f.writelines(to_write)
    eval_lines = return_report(output_file)
    return eval_lines
            
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
標注實體識別 
1.加載config_file的配置參數(shù)、tensorflow參數(shù)、是否使用gpu
2.在指定路徑下新建result_file、打開map_file文件讀取char_to_id, id_to_char, tag_to_id, id_to_tag
3.將tf_config入?yún)⒓虞d緩存
通過讀取ckpt_path下的ckpt文件加載訓練好的模型    
4. test_list = readText2Json("/data0/nlp/test/ner/test.txt") 將相應路徑下的測試文件內容轉換成dict

    strs = line.replace('\n','').split('\t')
    res = {}
    string = strs[0]
    res['string'] = string
    value_list = []
    wl = []
    tag_num = 0
    for str in strs[1:]:
        value = {}
        pos = find_last(str,':') //英國牛津大學:ORG
        word = str[:pos]    
        type = str[pos+1:]
        if not type == 'O':
            # print(type)
            tag_num += 1     //排除類型為O的計數(shù)
        value['word'] = word
        value['type'] = type
        value_list.append(value) //[{'type':'ORG','word':'英國牛津大學'}]
        wl.append(word)
    if len(value_list) == 0:
        continue
    res['value'] = value_list
    res['wl'] = wl
    res['tag_num'] = tag_num
    res_list.append(res) 

return res_list

5.遍歷res_list
for tests in test_list:
    line = tests['string'].replace(' ', '').replace('\t', '').replace('\s', '')
    res_list = tests['value']

{'tag_num': 1, 
'wl': ['英國牛津大學', '出版社', '出版', '的', '多種', '英語詞典', '的', '統(tǒng)稱'], 
'value': [{'type': 'ORG', 'word': '英國牛津大學'}, {'type': 'O', 'word': '出版社'}, {'type': 'O', 'word': '出版'}, {'type': 'O', 'word': '的'}, {'type': 'O', 'word': '多種'}, {'type': 'O', 'word': '英語詞典'}, {'type': 'O', 'word': '的'}, {'type': 'O', 'word': '統(tǒng)稱'}], 
'string': '英國牛津大學出版社出版的多種英語詞典的統(tǒng)稱'}    

inputs = input_from_line(string, char_to_id, word_list=wl)            
將string進行全角符號轉換為半角、html轉碼處理

inputs = list()
inputs.append([line])
inputs.append([[char_to_id[char] if char in char_to_id else char_to_id["<UNK>"]   //將line根據(jù)字典表轉為id
                for char in line]])
inputs.append([get_seg_features(line, word_list=word_list)])          //將line進行get_seg_features 矩陣處理        
inputs.append([[]])            

6.進行模型訓練得到訓練結果result            
result = model.evaluate_line(sess, inputs, id_to_tag)            

def evaluate_line(self, sess, inputs, id_to_tag):
    trans = self.trans.eval(session=sess)
    lengths, scores = self.run_step(sess, False, inputs)
    batch_paths = self.decode(scores, lengths, trans)
    tags = [id_to_tag[idx] for idx in batch_paths[0]] //得到的id轉為tag
    return result_to_json(inputs[0][0], tags)   //分詞標注結果轉換為json

entities = result['entities']            
[{'start': 0, 'end': 1, 'type': 'O', 'word': '英'}, {'start': 1, 'end': 6, 'type': 'ORGANIZATION', 'word': '國牛津大學'}, {'start': 6, 'end': 9, 'type': 'O', 'word': '出版社'}, {'start': 9, 'end': 11, 'type': 'O', 'word': '出版'}, {'start': 11, 'end': 12, 'type': 'O', 'word': '的'}, {'start': 12, 'end': 14, 'type': 'O', 'word': '多種'}, {'start': 14, 'end': 16, 'type': 'O', 'word': '英語'}, {'start': 16, 'end': 18, 'type': 'O', 'word': '詞典'}, {'start': 18, 'end': 19, 'type': 'O', 'word': '的'}, {'start': 19, 'end': 21, 'type': 'O', 'word': '統(tǒng)稱'}]            

7.遍歷entities,排除掉type為O的數(shù)據(jù),將標準答案 res_list 中的該下標的res的word、    type和識別結果 entities    中的type、word作為一行l(wèi)in寫入到result_file中。
  并統(tǒng)計正確結果的個數(shù)
-------------------------
for tests in test_list:
    test_acc += tag_num
-------------------------
  
for index, i in enumerate(entities):
    word = i['word']
    type = i['type']
    if index > len(res_list)-1:
        break
    # if type == 'O' and res_list[index]['type'] == 'O':
    #     continue
    if type == 'O':
        continue
    test_rec += 1
    lin = res_list[index]['word']+'\t'+res_list[index]['type']+'\t'+type+'\t'+word+'\n'
    start_in = 0
    end_in = -1
    if index > 5:
        start_in = index - 5
    if len(res_list) - index > 5:
        end_in = index + 5
    result_file.write(lin)
    for j in res_list[start_in:end_in]:
        if word == j['word'] and type == j['type']:
            test_right = test_right + 1
            break            

8.打印準確率、召回率等相關信息
zq = round(test_right / test_rec, 4) * 100
zh = round(test_right / test_acc, 4) * 100
f1 = round(2 * zq * zh / (zq + zh))
print('總標簽數(shù):{},識別標簽數(shù):{},識別對數(shù)量:{},準確率:{},召回率:{},f1:{}'.format(test_acc, test_rec, test_right, zq, zh, f1))

總標簽數(shù):8773,識別標簽數(shù):12260,識別對數(shù)量:3542,準確率:28.89,召回率:40.37,f1:34

test_acc:標準答案中所有排除other類型的標簽個數(shù)
test_rec:通過模型實體識別后的結果中實際識別的非other類型標簽的總數(shù)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
分類模型訓練:
1.準備post.xls、other.xls文件
train_datas = []
data = pd.read_excel(constant.clfytrain_path + '/{}'.format(file_name),  header=None)
將文件內容讀取到train_datas中
將兩個excel文件中的數(shù)據(jù)根據(jù)0軸(列)進行融合
pn = pd.concat(train_datas,  ignore_index=True)

到此,關于“tensorflow怎么配置”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI