国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Tensorflow實現(xiàn)訓練數(shù)據(jù)的加載—模型搭建訓練保存—模型調用和加載全流程

這篇具有很好參考價值的文章主要介紹了Tensorflow實現(xiàn)訓練數(shù)據(jù)的加載—模型搭建訓練保存—模型調用和加載全流程。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1.Tesorflow訓練模型的數(shù)據(jù)加載

  • ?將tensorflow的訓練數(shù)據(jù)數(shù)組(矩陣)保存為.npy的數(shù)據(jù)格式。為后續(xù)的模型訓練提供便捷的方法。例如如下:
import numpy as np
x=np.random.rand(100,7,9)#x是訓練數(shù)據(jù),這有100條數(shù)據(jù),每一條有7*9個特征
np.save(r"C:\結果\y_train_feature.npy",feature)#feature是訓練數(shù)據(jù)矩陣
  • ?加載.npy訓練數(shù)據(jù)和測試數(shù)組(矩陣),加載后需要調整數(shù)據(jù)的形狀以滿足設計模型的輸入輸出需求,不然無法訓練模型。
import numpy as np

 '''加載訓練和測試數(shù)據(jù)'''
y_train_feature=np.load('C:\結果\y_train_feature.npy')
y_test_feature=np.load('C:\結果\y_test_feature.npy')

'''加載訓練和測試的標簽'''
y_train=np.load('C:\結果\y_train.npy')
y_test=np.load('C:\結果\y_test.npy')
    
'''調整數(shù)據(jù)為模型輸入輸出所需要的形狀'''
y_test_feature=y_test_feature.reshape(-1,7,129)
y_train_feature=y_train_feature.reshape(-1,7,129)
y_test=y_test.reshape(-1,129)
y_train=y_train.reshape(-1,129)
  

?2.Tensorflow模型搭建的訓練和保存

  • 這里可以采用自定義層和tensorflow的API搭建網(wǎng)絡模型,以API為例子搭建多層LSTM網(wǎng)絡模型用于訓練。
import tensorflow as tf
from tensorflow import  keras
from keras.models import  Model
from keras.layers import Input, MaxPooling1D,Dense, Conv1D, Conv2D, Dropout, Flatten,\
 BatchNormalization, Reshape, Activation, concatenate,SeparableConv2D,LSTM,GRU,Conv2DTranspose,SimpleRNN
from keras.layers.pooling import MaxPooling2D


 '''模型輸入'''
input_feature = Input(shape=y_train_feature.shape[1:], name='input_feature')

  '''模型搭建LSTM'''
fc1=LSTM(512,return_sequences=True)(input_feature)
fc2=LSTM(512,return_sequences=True)(fc1)
fc3=LSTM(512,return_sequences=True)(fc2)
fc4=LSTM(512)(fc3)
'''全連接的輸出層'''
output_2 = Dense(129,activation='linear',kernel_initializer='random_uniform',\
                     bias_initializer='random_uniform',name='output1')(fc4)
   """以Model來組合整個網(wǎng)絡"""
model = Model(inputs= input_feature, outputs=output_2)
model.summary()#察看網(wǎng)絡架構
  • ?tensorflow模型的訓練,優(yōu)化器的選擇,損失函數(shù)的設置,批量大小,學習率大小,訓練epoch次數(shù),最優(yōu)模型的保存等操作。
adam=Adam(lr=0.0001,decay=1e-6)#優(yōu)化器的選擇
model.compile(optimizer=adam,
          loss='mae',#均方誤差
          metrics=['mae'])#平均絕對誤差
'''訓練網(wǎng)絡'''

earlyStopping = callbacks.EarlyStopping(monitor='val_mae',patience=5,mode='min')

#保存模型的路徑
filepath = "weights-improvement-{epoch:02d}-{val_mae:.2f}.h5"


#在每個訓練期(epoch)后保存模型
#period:檢查點之間的間隔(epoch數(shù))
checkpoint = callbacks.ModelCheckpoint(filepath, monitor='val_mae', verbose=1, save_best_only=True,
                            mode='min',save_weights_only=False,period=1)

print('Training------')
   
model.fit(y_train_feature,y_train,epochs=800,batch_size=128,verbose=1,validation_data=(y_test_feature,y_test),shuffle=True,callbacks=[earlyStopping,checkpoint])

model.save(r'new_models_ripleinputV7.h5')

?3.Tensorflow模型的調用

  • 訓練好并保存后的模型,調用時可以采用 load_model() 方法獲得保存后的模型。
from keras.models import load_model
import numpy as np

model = tf.keras.models.load_model(r"保存模型的路徑\LSTM.h5")
'''輸入數(shù)據(jù)獲得模型輸出結果'''
output=model.predict(input_feature)#input_feature形狀需要滿足模型輸入的形狀要求

'''將張量形式的輸出轉化為numpy數(shù)組的形式'''
output=np.array(output)

4.整體代碼實現(xiàn)

  • tensorflow網(wǎng)絡模型的訓練完整實現(xiàn)(API網(wǎng)絡搭建)的形式。自定義的網(wǎng)絡模型可采用同樣的方法訓練模型。
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 11 19:47:21 2021

@author: 茶墨先生
"""

'''導入需要的包'''
import tensorflow as tf
from tensorflow import  keras
from tensorflow.keras import  layers,Sequential,datasets
from keras import regularizers,callbacks 
tf.compat.v1.disable_eager_execution()
from keras import backend as K
from keras.datasets import mnist
from keras.optimizers import Adam
import numpy as np
from keras.models import  Model
from keras.layers import Input, MaxPooling1D,Dense, Conv1D, Conv2D, Dropout, Flatten,\
 BatchNormalization, Reshape, Activation, concatenate,SeparableConv2D,LSTM,GRU,Conv2DTranspose,SimpleRNN
from keras.layers.pooling import MaxPooling2D
  
#自定義模型
'''訓練'''
def Train():
    '''加載訓練數(shù)據(jù)'''
    y_train_feature=np.load('C:\結果\y_train_speech_feature.npy')
    y_test_feature=np.load('C:\結果\y_test_speech_feature.npy')
    y_train=np.load('C:\結果\y_train.npy')
    y_test=np.load('C:\結果\y_test.npy')
    
    y_test_feature=y_test_feature.reshape(-1,7,129)
    y_train_feature=y_train_feature.reshape(-1,7,129)
    y_test=y_test.reshape(-1,129)
    y_train=y_train.reshape(-1,129)
    print("y_train: ",y_train.shape)
    print("y_train_speech_feature: ", y_train_feature.shape)
    
    
    '''構建需要的網(wǎng)絡模型'''
    input_feature = Input(shape=y_train_feature.shape[1:], name='input_feature')
    fc1=LSTM(512,return_sequences=True)(input_feature)
    fc2=LSTM(512,return_sequences=True)(fc1)
    fc3=LSTM(512,return_sequences=True)(fc2)
    fc4=LSTM(512)(fc3)
    output_2 = Dense(129,activation='linear',kernel_initializer='random_uniform',\
                     bias_initializer='random_uniform',name='output1')(fc4)
    """以Model來組合整個網(wǎng)絡"""
    model = Model(inputs= input_feature, outputs=output_2)
    model.summary()
    
    adam=Adam(lr=0.0001,decay=1e-6)
    model.compile(optimizer=adam,
              loss='mae',#均方誤差
              metrics=['mae'])#平均絕對誤差
    '''訓練網(wǎng)絡'''
    
    earlyStopping = callbacks.EarlyStopping(monitor='val_mae',patience=5,mode='min')
    
    #保存模型的路徑
    filepath = "weights-improvement-{epoch:02d}-{val_mae:.2f}.h5"
    
    
    #在每個訓練期(epoch)后保存模型
    #period:檢查點之間的間隔(epoch數(shù))
    checkpoint = callbacks.ModelCheckpoint(filepath, monitor='val_mae', verbose=1, save_best_only=True,
                                mode='min',save_weights_only=False,period=1)
    
    print('Training------')
   
    model.fit(y_train_feature,y_train,epochs=800,batch_size=128,verbose=1,validation_data=(y_test_feature,y_test),shuffle=True,callbacks=[earlyStopping,checkpoint])
    
    model.save(r'new_models_ripleinputV7.h5')

'''主函數(shù)調用'''
if __name__ =='__main__':
    
    '''訓練'''
    Train()


    



讀書,生活,旅行。感謝關注和支持!文章來源地址http://www.zghlxwxcb.cn/news/detail-742708.html

到了這里,關于Tensorflow實現(xiàn)訓練數(shù)據(jù)的加載—模型搭建訓練保存—模型調用和加載全流程的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • pytorch11:模型加載與保存、finetune遷移訓練

    pytorch11:模型加載與保存、finetune遷移訓練

    往期回顧 pytorch01:概念、張量操作、線性回歸與邏輯回歸 pytorch02:數(shù)據(jù)讀取DataLoader與Dataset、數(shù)據(jù)預處理transform pytorch03:transforms常見數(shù)據(jù)增強操作 pytorch04:網(wǎng)絡模型創(chuàng)建 pytorch05:卷積、池化、激活 pytorch06:權重初始化 pytorch07:損失函數(shù)與優(yōu)化器 pytorch08:學習率調整策略

    2024年02月01日
    瀏覽(21)
  • 人工智能(pytorch)搭建模型18-含有注意力機制的CoAtNet模型的搭建,加載數(shù)據(jù)進行模型訓練

    大家好,我是微學AI,今天我給大家介紹一下人工智能(pytorch)搭建模型18-pytorch搭建有注意力機制的CoAtNet模型模型,加載數(shù)據(jù)進行模型訓練。本文我們將詳細介紹CoAtNet模型的原理,并通過一個基于PyTorch框架的實例,展示如何加載數(shù)據(jù),訓練CoAtNet模型,從操作上理解該模型。

    2024年02月16日
    瀏覽(34)
  • 【Tensorflow】模型如何加載HDF文件數(shù)據(jù)集?

    如果每個樣本都被保存為一個單獨的 HDF5 文件,可以使用 `tf.data.Dataset.list_files` 函數(shù)來創(chuàng)建一個文件名數(shù)據(jù)集,然后使用 `tf.data.Dataset.interleave` 函數(shù)來并行讀取多個文件。 下面的示例展示了如何從多個 HDF5 文件中讀取數(shù)據(jù)并創(chuàng)建一個 `tf.data.Dataset` 對象: import h5py import tenso

    2023年04月24日
    瀏覽(18)
  • bert模型訓練,加載保存的模型Can‘t load tokenizer for ‘/content/drive/MyDrive/Colab Notebooks/classification_mode

    哈嘍! 我用Bert預測評論分數(shù),訓練好模型保存到文件夾后,再一次加載它出現(xiàn)了上述錯誤,不太明白為什么,請教各位! 這是第二次訓練這模型,也就是說我訓練了一次之后,再把第一次訓練的模型用新的數(shù)據(jù)訓練,提高它的精確度,是可以的把,為什么第一次訓練沒有報

    2024年02月11日
    瀏覽(22)
  • 音頻數(shù)據(jù)處理+模型訓練保存+Android模型移植

    音頻數(shù)據(jù)處理+模型訓練保存+Android模型移植

    音頻數(shù)據(jù)處理+模型訓練保存+Android模型移植 一個epoch , 表示: 所有的數(shù)據(jù)送入網(wǎng)絡中, 完成了一次前向計算 + 反向傳播的過程 把數(shù)據(jù)準備好,開始跑實驗 1.分割數(shù)據(jù)集 scirpt.walk_file(path,out_path) BirdsSong-2s-20spec 2.生成csv(script.py) 3.將wav音頻文件中的音頻浮點序列特征提出出來

    2024年01月21日
    瀏覽(18)
  • TensorFlow進行MNIST數(shù)據(jù)集手寫數(shù)字識別,保存模型并且進行外部手寫圖片測試

    TensorFlow進行MNIST數(shù)據(jù)集手寫數(shù)字識別,保存模型并且進行外部手寫圖片測試

    首先,你已經(jīng)配置好Anaconda3的環(huán)境,下載了TensorFlow模塊,并且會使用jupyter了,那么接下來就是MNIST實驗步驟。 數(shù)據(jù)集官網(wǎng)下載: MNIST handwritten digit database, Yann LeCun, Corinna Cortes and Chris Burges http://yann.lecun.com/exdb/mnist/ ? 將上面四個全部下載,都是數(shù)據(jù)集,其中前兩個是訓練集,

    2024年02月08日
    瀏覽(14)
  • TensorFlow學習:使用官方模型和自己的訓練數(shù)據(jù)進行圖片分類

    TensorFlow學習:使用官方模型和自己的訓練數(shù)據(jù)進行圖片分類

    教程來源:清華大佬重講機器視覺!TensorFlow+Opencv:深度學習機器視覺圖像處理實戰(zhàn)教程,物體檢測/缺陷檢測/圖像識別 注: 這個教程與官網(wǎng)教程有些區(qū)別,教程里的api比較舊,核心思想是沒有變化的。 上一篇文章 TensorFlow學習:使用官方模型進行圖像分類、使用自己的數(shù)據(jù)

    2024年02月08日
    瀏覽(31)
  • Mediapipe實戰(zhàn)——導出身體節(jié)點坐標并用TensorFlow搭建LSTM網(wǎng)絡來訓練自己的手勢檢測模型再部署到樹莓派4B

    Mediapipe實戰(zhàn)——導出身體節(jié)點坐標并用TensorFlow搭建LSTM網(wǎng)絡來訓練自己的手勢檢測模型再部署到樹莓派4B

    一、前言 ??在YouTube上看到up主——Nicholas Renotte的相關教程,覺得非常有用。使用他的方法,我訓練了能夠檢測四種手勢的模型,在這里和大家分享一下。 ??附上該up主的視頻鏈接Sign Language Detection using ACTION RECOGNITION with Python | LSTM Deep Learning Model ??視頻的代碼鏈接htt

    2024年02月02日
    瀏覽(24)
  • TensorFlow2進行CIFAR-10數(shù)據(jù)集動物識別,保存模型并且進行外部下載圖片測試

    TensorFlow2進行CIFAR-10數(shù)據(jù)集動物識別,保存模型并且進行外部下載圖片測試

    首先,你已經(jīng)安裝好anaconda3、創(chuàng)建好環(huán)境、下載好TensorFlow2模塊并且下載好jupyter了,那么我們就直接打開jupyter開始進行CIFAR10數(shù)據(jù)集的訓練。 第一步:下載CIFAR10數(shù)據(jù)集 下載網(wǎng)址:http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 將數(shù)據(jù)集下載到合適的路徑,方便模型訓練的時候調用

    2024年02月08日
    瀏覽(27)
  • tensorflow2模型保存和恢復

    tensorflow2模型保存和恢復

    有兩種方法可以保存模型: ·使用檢查點,一種簡單的在硬盤上保存變量的方法 ·使用SavedModel,模型結構及檢查點 檢查點不包含任何關于模型自身的描述:它們只是一種簡單的存儲參數(shù)并能讓開發(fā)者正確恢復它的方法。 SavedModel格式在保存參數(shù)值的基礎上加上了計算過程的序

    2024年02月11日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包