softmax 분류 기 python 구현
7393 단어 딥 러 닝
알고리즘 은 앤 드 류 의 과제 와 이 글 을 참고 했다.구체 적 으로 실현 되 었 을 때 가중치 감쇠 효과 가 더 좋 은 것 으로 나 타 났 다.
여기 서 여러분 이 제 프로그램 을 이해 하지 못 하 는 것 을 방지 하기 위해 서 제 가 여기 서 정 의 를 내 리 겠 습 니 다.
∇ΘjJ(Θ)=−x(i)(1{y(i)=j}−p(y(i)=j|x(i);Θ))+λΘj(1) p(y(i)=j|x(i);Θ)=eΘTjx(i)∑kl=1eΘTlx(i)(2) eΘTlx(i)(3)
데이터 세트
데이터 세트 와 KNN 의 그 박문 은 같은 데이터 세트 를 사용 합 니 다. 데이터 주소:https://github.com/WenDesi/lihang_book_algorithm/blob/master/data/train.csv
특징.
전체 그림 을 특징 으로 하 다.
코드
코드 가 GitHub 에 업로드 되 었 습 니 다.
이번 코드 는 python 3 입 니 다.
# encoding=utf8
import math
import pandas as pd
import numpy as np
import random
import time
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
class Softmax(object):
def __init__(self):
self.learning_step = 0.000001 #
self.max_iteration = 100000 #
self.weight_lambda = 0.01 #
def cal_e(self,x,l):
'''
3
'''
theta_l = self.w[l]
product = np.dot(theta_l,x)
return math.exp(product)
def cal_probability(self,x,j):
'''
2
'''
molecule = self.cal_e(x,j)
denominator = sum([self.cal_e(x,i) for i in range(self.k)])
return molecule/denominator
def cal_partial_derivative(self,x,y,j):
'''
1
'''
first = int(y==j) #
second = self.cal_probability(x,j) #
return -x*(first-second) + self.weight_lambda*self.w[j]
def predict_(self, x):
result = np.dot(self.w,x)
row, column = result.shape
#
_positon = np.argmax(result)
m, n = divmod(_positon, column)
return m
def train(self, features, labels):
self.k = len(set(labels))
self.w = np.zeros((self.k,len(features[0])+1))
time = 0
while time < self.max_iteration:
print('loop %d' % time)
time += 1
index = random.randint(0, len(labels) - 1)
x = features[index]
y = labels[index]
x = list(x)
x.append(1.0)
x = np.array(x)
derivatives = [self.cal_partial_derivative(x,y,j) for j in range(self.k)]
for j in range(self.k):
self.w[j] -= self.learning_step * derivatives[j]
def predict(self,features):
labels = []
for feature in features:
x = list(feature)
x.append(1)
x = np.matrix(x)
x = np.transpose(x)
labels.append(self.predict_(x))
return labels
if __name__ == '__main__':
print('Start read data')
time_1 = time.time()
raw_data = pd.read_csv('../data/train.csv', header=0)
data = raw_data.values
imgs = data[0::, 1::]
labels = data[::, 0]
# 2/3 , 1/3
train_features, test_features, train_labels, test_labels = train_test_split(
imgs, labels, test_size=0.33, random_state=23323)
# print train_features.shape
# print train_features.shape
time_2 = time.time()
print('read data cost '+ str(time_2 - time_1)+' second')
print('Start training')
p = Softmax()
p.train(train_features, train_labels)
time_3 = time.time()
print('training cost '+ str(time_3 - time_2)+' second')
print('Start predicting')
test_predict = p.predict(test_features)
time_4 = time.time()
print('predicting cost ' + str(time_4 - time_3) +' second')
score = accuracy_score(test_labels, test_predict)
print("The accruacy socre is " + str(score))
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
caffe 데이터 구조 깊이 학습 (4) - blob 데이터 구조 blob. hpp 파일 상세 해석이 줄 은 shape 벡터 를 통 해 Blob 의 모양 을 바 꾸 는 또 다른 변형 함 수 를 정의 합 니 다. 이 줄 은 Blob 모양 의 함 수 를 읽 고 구성원 변수 shape 로 돌아 가 는 것 을 정의 합 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.