import os
import cv2
import xlwt
import xlrd
import numpy as np
from skimage import feature as skif
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, mean_absolute_error, f1_score, mutual_info_score
from sklearn.metrics.pairwise import pairwise_kernels, pairwise_distances
from sklearn.base import ClassifierMixin, BaseEstimator
from sklearn.utils.validation import check_X_y
from sklearn import preprocessing
class KELMOR(ClassifierMixin, BaseEstimator):
def __init__(self, C=100, method="full", S=None, eps=1e-5, kernel="linear", gamma=0.1, degree=3, coef0=1, kernel_params=None):
self.C = C
self.kernel = kernel
self.method = method
self.S = S
self.eps = eps
self.gamma = gamma
self.degree = degree
self.coef0 = coef0
self.kernel_params = kernel_params
def fit(self, X, y):
X, y = check_X_y(X, y)
self.X, self.y = X, y
n, d = X.shape
# ---------------规范化类别标签:0,1,2,3,4,5-----------------
self.le_ = preprocessing.LabelEncoder()
self.le_.fit(y)
y = self.le_.transform(y)
# --------------------------------------------------------
classes = np.unique(y)
nclasses = len(classes)
self.M = np.array([[(i - j) ** 2 for i in range(nclasses)] for j in range(nclasses)])
T = self.M[y, :]
K = self._get_kernel(X)
if self.method == "full":
self.beta = np.linalg.inv((1 / self.C) * np.eye(n) + K).dot(T)
else:
raise ValueError("Invalid value for argument 'method'.")
return self
def predict(self, X):
K = self._get_kernel(X, self.X)
coded_preds = K.dot(self.beta)
# print("coded_preds::",coded_preds.shape)
predictions = np.argmin(np.linalg.norm(coded_preds[:, None] - self.M, axis=2, ord=1), axis=1)
predictions = self.le_.inverse_transform(predictions)
return predictions
def _get_kernel(self, X, Y=None):
if callable(self.kernel):
params = self.kernel_params or {}
else:
params = {'gamma': self.gamma,
'degree': self.degree,
'coef0': self.coef0}
return pairwise_kernels(X, Y, metric=self.kernel, filter_params=True, **params)
@property
def _pairwise(self):
return self.kernel == "precomputed"
def predict_proba(self,X):
K = self._get_kernel(X, self.X)
coded_tmp = K.dot(self.beta)
predictions = np.linalg.norm(coded_tmp[:, None] - self.M, axis=2, ord=2)
predictions = -predictions
predictions = np.exp(predictions)
predictions_sum = np.sum(predictions, axis=1, keepdims=True)
proba_matrix = predictions / predictions_sum
return proba_matrix
# def getLbpData(image, hist_size=256, lbp_radius=1, lbp_point=8):
# image = cv2.resize(image, (300, 300), interpolation=cv2.INTER_CUBIC)
# # 使用LBP方法提取图像的纹理特征.
# lbp = skif.local_binary_pattern(image, lbp_point, lbp_radius, 'default')
# # 统计图像的直方图
# max_bins = int(lbp.max() + 1)
# # hist size:256
# hist, _ = np.histogram(lbp, normed=True, bins=max_bins, range=(0, max_bins))
# return hist
hog=cv2.HOGDescriptor()
def getHOGData(image):
image = cv2.resize(image, (150, 150), interpolation=cv2.INTER_CUBIC)
h = hog.compute(image,winStride=(64,128),padding=(0,0))
h_trans=h.transpose()
return h_trans
data = []
label = []
IMAGES_DIR = os.path.join(os.path.dirname(__file__), r'D:\FG-NET\ImagesClear')
book = xlrd.open_workbook(r"D:\FG-NET\meta.xls")
table = book.sheet_by_index(0)
for name in table.col_values(0):
print(name)
image = cv2.imread(os.path.join(IMAGES_DIR, name),0)
# print(image)
# lbpdata = getLbpData(image)
lbpdata = getHOGData(image)
print("lbpdata:",lbpdata.shape)
print("lbpdata=",type(lbpdata))
data.append(lbpdata)
for lab in table.col_values(2):
label.append(lab)
# -------------------------------------------
data = np.array(data)
print(data.shape)
label = np.array(label)
print(label.shape)
train_X,test_X,train_y,test_y = train_test_split(data,label,test_size=0.5)
model = SVC(kernel='rbf',C=0.001)
model.fit(train_X,train_y)
y_hat = model.predict(test_X)
ACC = accuracy_score(y_hat, test_y)
MAE = mean_absolute_error(y_hat, test_y)
MI = mutual_info_score(y_hat, test_y)
print("ACC===",ACC)
print("MAE===",MAE)
print("MI===",MI)
model_2 = KELMOR(C=10, kernel='rbf', gamma=0.001)
model_2.fit(train_X,train_y)
y_hat = model_2.predict(test_X)
ACC = accuracy_score(y_hat, test_y)
MAE = mean_absolute_error(y_hat, test_y)
MI = mutual_info_score(y_hat, test_y)
print("ACC===",ACC)
print("MAE===",MAE)
print("MI===",MI)
05-27
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)