Python代码:采用协同表示分类器处理高光谱数据(.mat数据)进行图像分类,并展示图片
时间: 2024-03-12 11:50:26 浏览: 253
Python-一个用于图像分类的一体化深度学习工具包
好的,以下是Python代码示例,使用协同表示分类器对高光谱数据进行图像分类,并展示图片:
```python
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from scipy.linalg import pinv2
# 读取数据
data = sio.loadmat('Indian_pines_corrected.mat')['indian_pines_corrected']
labels = sio.loadmat('Indian_pines_gt.mat')['indian_pines_gt']
height, width, bands = data.shape
X = np.reshape(data, (height*width, bands))
y = np.reshape(labels, -1)
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 协同表示分类器
class SRC():
def __init__(self, lamda=0.1):
self.lamda = lamda
def fit(self, X, y):
self.X = X
self.y = y
def predict(self, X_test):
y_pred = []
for i in range(X_test.shape[0]):
x = X_test[i].reshape(-1, 1)
A = self.X.T
G = np.dot(A, A.T) + self.lamda*np.identity(A.shape[0])
w = np.dot(pinv2(G), A)
c = np.dot(w, x)
r = x - np.dot(A, c)
residuals = np.sum(r**2, axis=0)
idx = np.argmin(residuals)
y_pred.append(self.y[idx])
return np.array(y_pred)
# 训练分类器
clf = SRC()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# 测试准确率
acc = accuracy_score(y_test, y_pred)
print('Accuracy:', acc)
# 展示图片
plt.figure()
plt.imshow(np.reshape(y_test, (height, width)))
plt.title('Ground Truth')
plt.colorbar()
plt.figure()
plt.imshow(np.reshape(y_pred, (height, width)))
plt.title('Predicted Labels')
plt.colorbar()
plt.show()
```
其中,`Indian_pines_corrected.mat`和`Indian_pines_gt.mat`是高光谱数据和标签的文件。代码中首先读取数据,并将高光谱数据转换为二维矩阵,标签转换为一维数组。然后使用`train_test_split`函数将原始数据集分割为训练集和测试集,使用`StandardScaler`进行特征缩放。接着定义了一个协同表示分类器`SRC`,其中`fit`方法用于训练分类器,`predict`方法用于预测新的样本。在`predict`方法中,使用协同表示的思想,通过求解线性方程组得到系数向量,然后计算残差并选择最相似的训练样本作为预测结果。最后,使用`accuracy_score`函数计算预测准确率,并展示原始标签和预测标签的图片。
阅读全文