2dcnn高光谱图像分类代码
时间: 2023-08-30 09:10:30 浏览: 188
基于意光谱先验的多方向网络实现高光谱图像分类附python代码.zip
以下是一个基于2D卷积神经网络(2DCNN)的高光谱图像分类代码示例:
```python
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from sklearn.model_selection import train_test_split
# 加载高光谱图像数据
data = np.load('data.npy')
labels = np.load('labels.npy')
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2)
# 将数据集重塑为2D图像格式
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1)
# 定义2D卷积神经网络模型
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(X_train.shape[1], X_train.shape[2], 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, batch_size=128, epochs=10, verbose=1, validation_data=(X_test, y_test))
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
请注意,代码中的数据和标签需要替换为您自己的高光谱图像数据和相应的标签。此外,您还可以调整模型的超参数(如卷积核大小、层数、节点数等)以获得更好的性能。
阅读全文