[英]Multinomial logistic softmax regression with SGD
我正在嘗試從頭開始建立可以對MNIST圖像(手寫數字)進行分類的模型。 該模型需要輸出一個概率列表,該概率列表表示輸入圖像是某個特定數字的可能性。
這是我到目前為止的代碼:
from sklearn.datasets import load_digits
import numpy as np
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis=0)
digits = load_digits()
features = digits.data
targets = digits.target
train_count = int(0.8 * len(features))
train_x = features[: train_count]
train_y = targets[: train_count]
test_x = features[train_count:]
test_y = targets[train_count:]
bias = np.random.rand()
weights = np.random.rand(len(features[0]))
rate = 0.02
for i in range(1000):
for i, sample in enumerate(train_x):
prod = np.dot(sample, weights) - bias
soft = softmax(prod)
predicted = np.argmax(soft) + 1
error = predicted - train_y[i]
weights -= error * rate * sample
bias -= rate * error
# print(error)
我正在嘗試構建模型,以便它使用隨機梯度下降,但是對於傳遞給softmax函數的內容我有些困惑。 我理解它應該期望有一個數字向量,但是我習慣(在構建一個小的NN時)是該模型應該產生一個數字,然后將其傳遞給激活函數,從而產生預測。 在這里,我感覺好像錯過了一步,我不知道這是什么。
在最簡單的實現中,您的最后一層(恰好在softmax之前)應該確實輸出10維矢量,該值將被softmax壓縮為[0, 1]
。 這意味着weights
應為形狀[features, 10]
的矩陣,而bias
應為[10]
向量。
除此之外,您應該對 train_y
標簽進行一次熱編碼, train_y
每個項目轉換為[0, 0, ..., 1, ..., 0]
向量。 因此train_y
的形狀為[size, 10]
。
看一下Logistic回歸示例 -它位於tensorflow中,但是該模型可能與您的模型相似:它們使用768個特征(所有像素),針對標簽的一鍵編碼和單個隱藏層。 他們還使用迷你批處理來加快學習速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.