DL之Keras:基于Keras框架建立模型實(shí)現(xiàn)【預(yù)測(cè)】功能的簡(jiǎn)介、設(shè)計(jì)思路,、案例分析,、代碼實(shí)現(xiàn)之詳細(xì)攻略(經(jīng)典,建議收藏)
Keras框架使用分析
Keras框架設(shè)計(jì)思路
案例分析
1、實(shí)現(xiàn)分類預(yù)測(cè):通過Keras建立模型,最終得到的模型能進(jìn)行兩種預(yù)測(cè),一是判斷出類別,二是給出屬于相應(yīng)類別概率,。
(1),、在Keras中,可以利用predict_class()函數(shù)來完成,利用最終的模型預(yù)測(cè)新數(shù)據(jù)樣本的類別。但是,這個(gè)函數(shù)僅適用于Sequential模型,不適于使用功能式API開發(fā)的模型,。
對(duì)三個(gè)實(shí)例預(yù)測(cè):
# 建立一個(gè)新的分類模型
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import MinMaxScaler
# 生成二分類數(shù)據(jù)集
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.transform(X)
# 定義并擬合最終模型
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, y, epochs=500, verbose=0)
# 新的未知數(shù)據(jù)實(shí)例
Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1)
Xnew = scalar.transform(Xnew)
# 作出預(yù)測(cè)
ynew = model.predict_classes(Xnew)
# 顯示輸入和輸出
for i in range(len(Xnew)):
print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))
對(duì)一個(gè)實(shí)例預(yù)測(cè):需要將它包裝變成一個(gè)數(shù)組的形式,。以便傳給predict_classes()函數(shù)
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import MinMaxScaler
from numpy import array
# 生成一個(gè)二分類數(shù)據(jù)集
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.transform(X)
# 定義并擬合最終的新模型
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, y, epochs=500, verbose=0)
# 未知的新實(shí)例
Xnew = array([[0.89337759, 0.65864154]])
# 作出預(yù)測(cè)
ynew = model.predict_classes(Xnew)
# 顯示輸入輸出
print("X=%s, Predicted=%s" % (Xnew[0], ynew[0]))
代碼實(shí)現(xiàn)
1、基于Keras設(shè)計(jì)的簡(jiǎn)單二分類問題開發(fā)的神經(jīng)網(wǎng)絡(luò)模型案例
# 訓(xùn)練一個(gè)最終分類的模型
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import MinMaxScaler
# 生成一個(gè)二分類問題的數(shù)據(jù)集
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.transform(X)
# 定義并擬合模型
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, y, epochs=200, verbose=0)