svm遥感图像 python
时间: 2023-09-20 13:03:32 浏览: 104
使用SVM进行遥感图像分类的Python代码示例:
1. 导入必要的库
```python
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from osgeo import gdal
```
2. 读取遥感图像数据
```python
def read_img(filename):
dataset = gdal.Open(filename)
im_width = dataset.RasterXSize
im_height = dataset.RasterYSize
im_geotrans = dataset.GetGeoTransform()
im_proj = dataset.GetProjection()
im_data = dataset.ReadAsArray(0, 0, im_width, im_height)
im_data = np.transpose(im_data, (1, 2, 0))
im_band = im_data.reshape(im_width * im_height, -1)
return im_band, im_data, im_width, im_height, im_geotrans, im_proj
```
3. 数据预处理
```python
def preprocessing(X, y):
# 标准化
scaler = StandardScaler().fit(X)
X_std = scaler.transform(X)
# PCA降维
pca = PCA(n_components=30).fit(X_std)
X_pca = pca.transform(X_std)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.2, random_state=1)
return X_train, X_test, y_train, y_test
```
4. 训练模型并进行预测
```python
def train_predict(X_train, X_test, y_train, y_test):
# SVM模型训练
clf = svm.SVC(kernel='rbf', C=1.0, gamma='auto')
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
return acc
```
5. 完整代码示例
```python
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from osgeo import gdal
def read_img(filename):
dataset = gdal.Open(filename)
im_width = dataset.RasterXSize
im_height = dataset.RasterYSize
im_geotrans = dataset.GetGeoTransform()
im_proj = dataset.GetProjection()
im_data = dataset.ReadAsArray(0, 0, im_width, im_height)
im_data = np.transpose(im_data, (1, 2, 0))
im_band = im_data.reshape(im_width * im_height, -1)
return im_band, im_data, im_width, im_height, im_geotrans, im_proj
def preprocessing(X, y):
# 标准化
scaler = StandardScaler().fit(X)
X_std = scaler.transform(X)
# PCA降维
pca = PCA(n_components=30).fit(X_std)
X_pca = pca.transform(X_std)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.2, random_state=1)
return X_train, X_test, y_train, y_test
def train_predict(X_train, X_test, y_train, y_test):
# SVM模型训练
clf = svm.SVC(kernel='rbf', C=1.0, gamma='auto')
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
return acc
if __name__ == '__main__':
# 读取数据
filename = 'filename.tif'
im_band, im_data, im_width, im_height, im_geotrans, im_proj = read_img(filename)
# 获取标签
y = np.loadtxt('labels.txt')
# 预处理数据
X_train, X_test, y_train, y_test = preprocessing(im_band, y)
# 训练并预测
acc = train_predict(X_train, X_test, y_train, y_test)
print('Accuracy:', acc)
```
阅读全文