import numpy as np
import random
from matplotlib import pyplot as plt
import scipy.io as scio
from sklearn import svm
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
'''优化函数'''
def fun(X):
classifier=svm.SVC(C=X[0],kernel='rbf',gamma=X[1])
classifier.fit(train_wine,train_label.ravel())
tes_label=classifier.predict(test_wine)
output = 1 - accuracy_score(test_label,tes_label)
return output
''' 种群初始化函数 '''
def initial(pop, dim, ub, lb):
X = np.zeros([pop, dim])
for i in range(pop):
for j in range(dim):
X[i, j] = random.random()*(ub[j] - lb[j]) + lb[j]
print(type(X))
return X,lb,ub
'''边界检查函数'''
def BorderCheck(X,ub,lb,pop,dim):
for i in range(pop):
for j in range(dim):
if X[i,j]>ub[j]:
X[i,j] = ub[j]
elif X[i,j]<lb[j]:
X[i,j] = lb[j]
return X
'''计算适应度函数'''
def CaculateFitness(X,fun):
pop = X.shape[0]
fitness = np.zeros([pop, 1])
for i in range(pop):
fitness[i] = fun(X[i, :])
return fitness
'''适应度排序'''
def SortFitness(Fit):
fitness = np.sort(Fit, axis=0)
index = np.argsort(Fit, axis=0)
return fitness,index
'''根据适应度对位置进行排序'''
def SortPosition(X,index):
Xnew = np.zeros(X.shape)
for i in range(X.shape[0]):
Xnew[i,:] = X[index[i],:]
return Xnew
'''麻雀发现者更新'''
def PDUpdate(X,PDNumber,ST,Max_iter):
X_new = np.zeros(X.shape)
R2 = random.random()
for j in range(PDNumber):
if R2<ST:
X_new[j,:] = X[j,:]*np.exp(-j/(random.random()*Max_iter))
else:
X_new[j,:] = X[j,:] + np.random.randn()*np.ones([1,dim])
return X_new
'''麻雀加入者更新'''
def JDUpdate(X,PDNumber,pop,dim):
X_new = np.zeros(X.shape)
for j in range(PDNumber+1,pop):
if j>(pop - PDNumber)/2 + PDNumber:
X_new[j,:]= np.random.randn()*np.exp((X[-1,:] - X[j,:])/j**2)
else:
A = np.ones([dim,1])
for a in range(dim):
if(random.random()>0.5):
A[a]=-1
AA = np.dot(A,np.linalg.inv(np.dot(A.T,A)))
X_new[j,:]= X[1,:] + np.abs(X[j,:] - X[1,:])*AA.T
return X_new
'''危险更新'''
def SDUpdate(X,pop,SDNumber,fitness,BestF):
X_new = np.zeros(X.shape)
Temp = range(pop)
RandIndex = random.sample(Temp, pop)
SDchooseIndex = RandIndex[0:SDNumber]
for j in range(SDNumber):
if fitness[SDchooseIndex[j]]>BestF:
X_new[SDchooseIndex[j],:] = X[1,:] + np.random.randn()*np.abs(X[SDchooseIndex[j],:] - X[1,:])
elif fitness[SDchooseIndex[j]] == BestF:
K = 2*random.random() - 1
X_new[SDchooseIndex[j],:] = X[SDchooseIndex[j],:] + K*(np.abs( X[SDchooseIndex[j],:] - X[-1,:])/(fitness[SDchooseIndex[j]] - fitness[-1] + 10E-8))
return X_new
'''麻雀搜索算法'''
def SSA(pop,dim,lb,ub,Max_iter,fun):
ST = 0.6
PD = 0.7
SD = 0.2
PDNumber = int(pop*PD)
SDNumber = int(pop*SD)
X,lb,ub = initial(pop, dim, ub, lb)
fitness = CaculateFitness(X,fun)
fitness,sortIndex = SortFitness(fitness)
X = SortPosition(X,sortIndex)
GbestScore = fitness[0]
GbestPositon = np.zeros([1,dim])
GbestPositon[0,:] = X[0,:]
Curve = np.zeros([MaxIter,1])
for i in range(MaxIter):
BestF = fitness[0]
X = PDUpdate(X,PDNumber,ST,Max_iter)
X = JDUpdate(X,PDNumber,pop,dim)
X = SDUpdate(X,pop,SDNumber,fitness,BestF)
X = BorderCheck(X,ub,lb,pop,dim)
fitness = CaculateFitness(X,fun)
fitness,sortIndex = SortFitness(fitness)
X = SortPosition(X,sortIndex)
if(fitness[0]<=GbestScore):
GbestScore = fitness[0]
GbestPositon[0,:] = X[0,:]
Curve[i] = GbestScore
return GbestScore,GbestPositon,Curve
'''主函数 '''
path= '../其他方法/chapter_WineClass.mat'
data = scio.loadmat(path)
winedata = np.transpose(data['wine'])
labeldata = np.transpose(data['wine_labels'])
train_wine=np.hstack((winedata[:,0:29],winedata[:,59:94],winedata[:,130:152]))
train_label = np.hstack((labeldata[:,0:29],labeldata[:,59:94],labeldata[:,130:152]))
test_wine = np.hstack((winedata[:,30:58],winedata[:,95:129],winedata[:,153:177]));
test_label = np.hstack((labeldata[:,30:58],labeldata[:,95:129],labeldata[:,153:177]))
min_max_scaler = preprocessing.MinMaxScaler()
train_wine = min_max_scaler.fit_transform(train_wine)
test_wine = min_max_scaler.fit_transform(test_wine)
train_wine = train_wine.T
test_wine = test_wine.T
train_label = train_label.T
test_label = test_label.T
pop = 2
MaxIter = 2
dim = 2
lb = np.matrix([[0.1],[0.1]])
ub = np.matrix([[200],[200]])
GbestScore,GbestPositon,Curve = SSA(pop,dim,lb,ub,MaxIter,fun)
print('最优适应度值:',GbestScore)
print('c,g最优解:',GbestPositon)
classifier=svm.SVC(C=GbestPositon[0,0],kernel='rbf',gamma=GbestPositon[0,1])
classifier.fit(train_wine,train_label.ravel())
tra_label=classifier.predict(train_wine)
tes_label=classifier.predict(test_wine)
print("训练集准确率:", accuracy_score(train_label,tra_label) )
print("测试集准确率:", accuracy_score(test_label,tes_label) )
plt.figure(1)
plt.plot(test_label,'*',label = "True")
plt.plot(tes_label,'o',label = "predict")
plt.xlabel("Test Case")
plt.ylabel("Case Label")
plt.grid(True)
plt.legend(bbox_to_anchor=(1.0, 1), loc=1, borderaxespad=0.)
plt.show()