https://www.cnblogs.com/Determined22/p/6362951.html
http://deeplearning.stanford.edu/wiki/index.php/Softmax%E5%9B%9E%E5%BD%92
http://www.360doc.com/content/18/0407/21/32196507_743620592.shtml
将模型对一个样本 (xi,yi)(xi,yi) 的后验概率估计组成列向量
#theta.shape==(k,n+1)
#lenda是正则化系数/权重衰减项系数,alpha是学习率
def J(X,classLabels,theta,alpha,lenda):
bin_classLabels=label_binarize(classLabels,classes=np.unique(classLabels).tolist()).reshape((m,k)) #二值化 (m*k)
dataSet=np.concatenate((X,np.ones((m,1))),axis=1).reshape((m,n+1)).T #转换为(n+1,m)
theta_data=theta.dot(dataSet) #(k,m)
theta_data = theta_data - np.max(theta_data) #k*m
prob_data = np.exp(theta_data) / np.sum(np.exp(theta_data), axis=0) #(k*m) //与逻辑回归的不同之处
#print(bin_classLabels.shape,prob_data.shape
cost = (-1 / m) * np.sum(np.multiply(bin_classLabels,np.log(prob_data).T)) + (lenda / 2) * np.sum(np.square(theta)) #标量
#print(dataSet.shape,prob_data.shape)
grad = (-1 / m) * (dataSet.dot(bin_classLabels - prob_data.T)).T + lenda * theta #(k*N+1)
return cost,grad
def train(X,classLabels,theta,alpha=0.1,lenda=1e-4,maxiter=1000):
#options_ = {'maxiter': 400, 'disp': True}
#result =minimize(J(X,classLabels,theta,alpha,lenda), theta, method='L-BFGS-B', jac=True, options=options_)
#return result.x
for i in range(maxiter):
cost,grad=J(X,classLabels,theta,alpha,lenda)
theta=theta-alpha*grad
return theta
使用 SoftMax 回归或者是多个 Logistic 回归二分类解决多分类问题,取决于类别之间是否互斥,例如,如果有四个类别的音乐,分别为:古典音乐、乡村音乐、摇滚乐和爵士乐,那么可以假设每个训练样本只会被打上一个标签(即:一首歌只能属于这四种音乐类型的其中一种),此时你应该使用类别数 k = 4 的 SoftMax 回归。(如果在你的数据集中,有的歌曲不属于以上四类的其中任何一类,那么你可以添加一个“其他类”,并将类别数 k 设为5)。