實驗11-使用keras完成邏輯迴歸

阿飞藏泪發表於2024-04-27

版本python3.7 tensorflow版本為tensorflow-gpu版本2.6

執行結果:

程式碼:

import numpy as np

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
import matplotlib.pyplot as plt
from sklearn import datasets

# 樣本資料集,兩個特徵列,兩個分類二分類不需要onehot編碼,直接將類別轉換為0和1,分別代表正樣本的機率。
X,y=datasets.make_classification(n_samples=200, n_features=2, n_informative=2, n_redundant=0,n_repeated=0, n_classes=2, n_clusters_per_class=1)

# 構建神經網路模型
model = Sequential()
model.add(Dense(input_dim=2, units=1))
model.add(Activation('sigmoid'))

# 選定loss函式和最佳化器
model.compile(loss='binary_crossentropy', optimizer='sgd')

# 訓練過程
print('Training -----------')
for step in range(501):
    cost = model.train_on_batch(X, y)
    if step % 50 == 0:
        print("After %d trainings, the cost: %f" % (step, cost))

# 測試過程
print('\nTesting ------------')
cost = model.evaluate(X, y, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)

# 將訓練結果繪出
Y_pred = model.predict(X)
Y_pred = (Y_pred*2).astype('int')  # 將機率轉化為類標號,機率在0-0.5時,轉為0,機率在0.5-1時轉為1
# 繪製散點圖 引數:x橫軸 y縱軸
plt.subplot(2,1,1).scatter(X[:,0], X[:,1], c=Y_pred[:,0])
plt.subplot(2,1,2).scatter(X[:,0], X[:,1], c=y)
plt.show()

相關文章