網站首頁 編程語言 正文
Sequential模型和Functional模型區別
Sequential模型
只有一個輸入和輸出,而且網絡是層的線性堆疊
可以通過向Sequential
模型傳遞一個layer的list來構造該模型:
from keras.models import Sequential from keras.layers import Dense, Activation #Sequential的第一層需要接受一個關于輸入數據shape的參數,后面的各個層則可以自動的推導出中間數據的shape model = Sequential() model.add(Dense(32, input_shape=(784,))) model.add(Activation('relu'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) # Generate dummy data import numpy as np data = np.random.random((1000, 100)) labels = np.random.randint(2, size=(1000, 1)) # Train the model, iterating on the data in batches of 32 samples model.fit(data, labels, epochs=10, batch_size=32) # For a single-input model with 10 classes (categorical classification): model = Sequential() model.add(Dense(32, activation='relu', input_dim=100)) model.add(Dense(10, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Generate dummy data import numpy as np data = np.random.random((1000, 100)) labels = np.random.randint(10, size=(1000, 1)) # Convert labels to categorical one-hot encoding one_hot_labels = keras.utils.to_categorical(labels, num_classes=10) # Train the model, iterating on the data in batches of 32 samples model.fit(data, one_hot_labels, epochs=10, batch_size=32)
Functional模型
區別:
1.層對象接受張量為參數,返回一個張量。
2.輸入是張量,輸出也是張量的一個框架就是一個模型,通過Model
定義。
from keras.models import Sequential, Model from keras import layers from keras import Input """ # Sequential模型實現 seq_model = Sequential() seq_model.add(layers.Dense(32, activation='relu', input_shape=(64,))) seq_model.add(layers.Dense(32, activation='relu')) seq_model.add(layers.Dense(10, activation='softmax')) """ # 對應的函數式模型實現 input_tensor = Input(shape=(64,)) x = layers.Dense(32, activation='relu')(input_tensor) x = layers.Dense(32, activation='relu')(x) output_tensor = layers.Dense(10, activation='softmax')(x) model = Model(input_tensor, output_tensor) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels) # starts training model.summary() # 查看模型
3.所有的模型都是可調用的,就像層一樣
這種方式可以允許你快速的創建能處理序列信號的模型,你可以很快將一個圖像分類的模型變為一個對視頻分類的模型,只需要一行代碼:
from keras.layers import TimeDistributed # Input tensor for sequences of 20 timesteps, # each containing a 784-dimensional vector input_sequences = Input(shape=(20, 784)) # This applies our previous model to every timestep in the input sequences. # the output of the previous model was a 10-way softmax, # so the output of the layer below will be a sequence of 20 vectors of size 10. processed_sequences = TimeDistributed(model)(input_sequences)
4.構建具有多個輸入的模型或多個輸出的模型
from keras.models import Model from keras import layers from keras import Input text_vocabulary_size = 10000 question_vocabulary_size = 10000 answer_vocabulary_size = 500 # 文本輸入是一個長度可變的整數序列。注意,你可以選擇對輸入進行命名 text_input = Input(shape=(None,), dtype='int32', name='text') embedded_text = layers.Embedding( text_vocabulary_size, 64)(text_input) encoded_text = layers.LSTM(32)(embedded_text) question_input = Input(shape=(None,), dtype='int32', name='question') embedded_question = layers.Embedding( question_vocabulary_size, 32)(question_input) encoded_question = layers.LSTM(16)(embedded_question) # 將編碼后的問題和文本連接起來 concatenated = layers.concatenate([encoded_text, encoded_question], axis=-1) answer = layers.Dense(answer_vocabulary_size, activation='softmax')(concatenated) # 在模型實例化時,指定兩個輸入和輸出 model = Model([text_input, question_input], answer) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc']) import numpy as np num_samples = 1000 max_length = 100 text = np.random.randint(1, text_vocabulary_size, size=(num_samples, max_length)) question = np.random.randint(1, question_vocabulary_size, size=(num_samples, max_length)) answers = np.random.randint(answer_vocabulary_size, size=(num_samples)) answers = keras.utils.to_categorical(answers, answer_vocabulary_size) model.fit([text, question], answers, epochs=10, batch_size=128) # 使用輸入組成的字典來擬合(只有對輸入進行命名之后才能用這種方法)使用輸入組成的列表來擬合 model.fit({'text': text, 'question': question}, answers, epochs=10, batch_size=128)
from keras import layers from keras import Input from keras.models import Model vocabulary_size = 50000 num_income_groups = 10 posts_input = Input(shape=(None,), dtype='int32', name='posts') embedded_posts = layers.Embedding(256, vocabulary_size)(posts_input) x = layers.Conv1D(128, 5, activation='relu')(embedded_posts) x = layers.MaxPooling1D(5)(x) x = layers.Conv1D(256, 5, activation='relu')(x) x = layers.Conv1D(256, 5, activation='relu')(x) x = layers.MaxPooling1D(5)(x) x = layers.Conv1D(256, 5, activation='relu')(x) x = layers.Conv1D(256, 5, activation='relu')(x) x = layers.GlobalMaxPooling1D()(x) x = layers.Dense(128, activation='relu')(x) # 注意,輸出層都具有名稱 age_prediction = layers.Dense(1, name='age')(x) income_prediction = layers.Dense(num_income_groups, activation='softmax', name='income')(x) gender_prediction = layers.Dense(1, activation='sigmoid', name='gender')(x) model = Model(posts_input, [age_prediction, income_prediction, gender_prediction]) #制定不同的損失函數 model.compile(optimizer='rmsprop', loss=['mse', 'categorical_crossentropy', 'binary_crossentropy']) # 與上述寫法等效(只有輸出層具有名稱時才能采用這種寫法) model.compile(optimizer='rmsprop', loss={'age': 'mse', 'income': 'categorical_crossentropy', 'gender': 'binary_crossentropy'}) #假設 age_targets、income_targets 和gender_targets 都是 Numpy 數組 model.fit(posts, [age_targets, income_targets, gender_targets], epochs=10, batch_size=64) # 等效 model.fit(posts, {'age': age_targets, 'income': income_targets, 'gender': gender_targets}, epochs=10, batch_size=64) 由于,年齡回歸任務的均方誤差(MSE)損失值通常在 3~5 左右,而用于性別分類任務的交叉熵損失值可能低至 0.1。在這種情況下,為了平衡不同損失的貢獻,我們可以讓交叉熵損失的權重取 10,而 MSE 損失的權重取 0.5
model.compile(optimizer='rmsprop', loss=['mse', 'categorical_crossentropy', 'binary_crossentropy'], loss_weights=[0.25, 1., 10.]) # 等效 model.compile(optimizer='rmsprop', loss={'age': 'mse', 'income': 'categorical_crossentropy', 'gender': 'binary_crossentropy'}, loss_weights={'age': 0.25, 'income': 1., 'gender': 10.})
總結
原文鏈接:https://blog.csdn.net/weixin_38740463/article/details/90479319
相關推薦
- 2023-02-23 C語言整形提升舉例詳解_C 語言
- 2022-04-14 zsh: command not found:快速的解決方法
- 2022-08-21 Caffe卷積神經網絡視覺層Vision?Layers及參數詳解_python
- 2023-03-22 tkinter如何實現打開文件對話框并獲取文件絕對路徑_python
- 2022-09-03 Python?Opencv使用ann神經網絡識別手寫數字功能_python
- 2022-05-03 EF使用Code?First模式給實體類添加復合主鍵_實用技巧
- 2022-07-13 Android自定義View實現簡易畫板功能_Android
- 2022-07-16 遠程管理常用命令(ipconfig、ping等)
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支