實(shí)現(xiàn)功能
上篇文章介紹了用Squential搭建BP神經(jīng)網(wǎng)絡(luò),Squential可以搭建出上層輸出就是下層輸入的順序神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu),無(wú)法搭出一些帶有跳連的非順序網(wǎng)絡(luò)結(jié)構(gòu),這個(gè)時(shí)候我們可以選擇類class搭建封裝神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)。
-
第一步:import tensorflow as tf:導(dǎo)入模塊
-
第二步:制定輸入網(wǎng)絡(luò)的訓(xùn)練集和測(cè)試集
-
第三步:搭建網(wǎng)絡(luò)結(jié)構(gòu)
-
第四步:model.compile():配置訓(xùn)練方法
-
第五步:model.fit():執(zhí)行訓(xùn)練過(guò)程
-
第六步:model.summary():打印網(wǎng)絡(luò)結(jié)構(gòu)
實(shí)現(xiàn)代碼
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
class NeuralNetwork(tf.keras.Model):
def __init__(self, input_size, hidden_size, output_size):
super(NeuralNetwork, self).__init__()
self.dense1 = tf.keras.layers.Dense(hidden_size, activation='relu')
self.dense2 = tf.keras.layers.Dense(hidden_size, activation='relu')
self.dense3 = tf.keras.layers.Dense(output_size, activation='softmax')
def call(self, inputs):
x = self.dense1(inputs)
x = self.dense2(x)
x = self.dense3(x)
return x
# 加載鳶尾花數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target
# 數(shù)據(jù)預(yù)處理
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 創(chuàng)建模型實(shí)例
input_size = X.shape[1]
hidden_size = 64
output_size = len(set(y))
model = NeuralNetwork(input_size, hidden_size, output_size)
# 編譯模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 訓(xùn)練模型
model.fit(X_train, y_train, epochs=10, batch_size=32)
model.summary()
# 評(píng)估模型
test_loss, test_accuracy = model.evaluate(X_test, y_test)
實(shí)現(xiàn)效果
本人讀研期間發(fā)表5篇SCI數(shù)據(jù)挖掘相關(guān)論文,現(xiàn)在某研究院從事數(shù)據(jù)挖掘相關(guān)科研工作,對(duì)數(shù)據(jù)挖掘有一定認(rèn)知和理解,會(huì)結(jié)合自身科研實(shí)踐經(jīng)歷不定期分享關(guān)于python、機(jī)器學(xué)習(xí)、深度學(xué)習(xí)基礎(chǔ)知識(shí)與案例。
致力于只做原創(chuàng),以最簡(jiǎn)單的方式理解和學(xué)習(xí),關(guān)注我一起交流成長(zhǎng)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-718376.html
邀請(qǐng)三個(gè)朋友關(guān)注V訂閱號(hào):數(shù)據(jù)雜壇,即可在后臺(tái)聯(lián)系我獲取相關(guān)數(shù)據(jù)集和源碼,送有關(guān)數(shù)據(jù)分析、數(shù)據(jù)挖掘、機(jī)器學(xué)習(xí)、深度學(xué)習(xí)相關(guān)的電子書(shū)籍。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-718376.html
到了這里,關(guān)于Python深度學(xué)習(xí)實(shí)戰(zhàn)-基于class類搭建BP神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)分類任務(wù)(附源碼和實(shí)現(xiàn)效果)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!