和SVM的实现存在一定的相似性,要通过划分训练集的一部分作为验证集来确定超参数。在得出对应的评分之后,要求出对应的概率,同时利用梯度更新的时候,注意求导与SVM存在不同即可,具体实现见如下代码,准确率基本稳定在39%左右。
import numpy as np
import pickle as pic
class softmax:
weight=[]
l_rate=0
reg=0
def readData(self,file):
with open(file,'rb') as fo:
dict=pic.load(fo,encoding='bytes')
return dict
def getGradient(self,sample_train_data,sample_train_label,reg):
amount=sample_train_data.shape[0]
score=self.weight.dot(sample_train_data.T)
per_amount=np.max(score,axis=0)
score=score-per_amount
exp_score=np.exp(score)
per_sum=np.sum(exp_score,axis=0)
exp_score=exp_score/per_sum
exp_score[sample_train_label,range(amount)]-=1
gred=exp_score.dot(sample_train_data)/amount+reg*self.weight