-1

I have a segmentation shapefile made with e-cognition containing many polygons of which a part classified for the train file. I would like to classify them by applying labels (e.g. water, vegetation, etc.) to each class, 5 in my case. I've read around that this can be done with Random Forest. How can I do this?

img='C:/Users/Desktop/Mosaico.tif'
TRAIN = 'C:/Users/Utente/Desktop/Train/'
TEST = 'C:/Users/Utente/Desktop/Test/'

files = [f for f in os.listdir(TRAIN) if f.endswith('.shp')]
shapefiles = [os.path.join(TRAIN, f) for f in files if f.endswith('.shp')]
print(shapefiles)

['C:/Users/Utente/Desktop/Train/TrainPolig.shp']

How do I proceed? I am new to Python and would like to understand what to do.

0

You've already assigned the "scikit-learn" tag so I assume you want to use this library. Good choice. But at first you need something to open a shapefile and extract attributes. I would recommend geopandas:

http://geopandas.org/io.html

import geopandas as gpd

data = gpd.read_file('path/to/file')

It creates a data frame for which documentation you can find there:

https://pandas.pydata.org/

The point here is you need to have a data structure which can be used for training (and classification later too because it's the same schema). Scikit tools accept Numpy arrays but also Pandas data frames are fine. You just need to remove all the attributes you don't need.

Then you can start to work with Scikit-Learn. Random Forest Classifier documentation is here: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html It works exactly the same way as any other tool in this library (has different settings of course).

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier()

# X is a 2D array with the variables extracted from your shapefile
# Y is a target 1D array (variable that contains classification results)
# both are extracted from the training set/shapefile
clf.fit(X,Y)

At this point you've got a classifier which is ready to predict some stuff. I'd also recommend to do some cross validation and check performance (see scikit documentation).

To predict a single feature, you need to pass an array with variables (number of variables must match X columns):

# if X has 5 columns, for example
clf.predict([1,2,3,4,5])

Of course shapefiles contain multiple features but you don't need to use loop, you can also pass a 2D array.

And always check the documentation, there are multiple options you can change to improve performance.

The rest is just writing the result to a shapefile, should be pretty straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.