keras的簡單使用

Keras 是一個用 Python 編寫的高級神經網絡 API

官網:https://keras.io/zh/


from keras.models import Sequential  # 神經網絡各個層的容器
from keras.layers import Dense, Activation  # 安全求和的層 激活函數
from keras.optimizers import SGD  # 隨機梯度下降算法
from sklearn.datasets import load_iris  # 數據集
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split

iris = load_iris()
print(iris["target"])  # 標籤化
print(LabelBinarizer().fit_transform(iris["target"]))  # 標籤化
# 訓練集 測試集
train_data, test_data, train_target, test_target = train_test_split(iris.data, iris.target, test_size=20)
labels_train = LabelBinarizer().fit_transform(train_target)
labels_test = LabelBinarizer().fit_transform(test_target)

# 模型訓練
# 方式一  網絡結構
model = Sequential(
    [
        Dense(5, input_dim=4),  # 第一層輸出有5 輸入對應 4個屬性值
        Activation("relu"),  # 激活函數
        Dense(3),  # 可以省略
        Activation("sigmoid"),  # 激活函數
    ]
)
# 方式二
# model = Sequential()
# model.add(Dense(5,input=4)) # 一層一層往裏面添加

# 構建優化器
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)  # decay步長 實質因子0.9
model.compile(optimizer=sgd, loss="categorical_crossentropy")  # 優化器 sgd 損失函數 categorical_crossentropy
model.fit(train_data, labels_train, epochs=200, batch_size=40)  # 訓練200輪

print("測試結果:\n", model.predict_classes(test_data))  # 打印預測結果
model.save_weights("weights")  # 存  權重因子
model.load_weights('weights')  # 下次使用可以直接加載

iris["target"]:(輸出)

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]

01碼:(輸出)

鏈接 提取碼:grrn 

200輪訓練過程:

鏈接  提取碼:ml85 

測試結果:
 [1 2 2 2 2 2 0 0 1 2 2 1 2 0 2 1 1 0 1 1]

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章