<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bernardin Ligan on Medium]]></title>
        <description><![CDATA[Stories by Bernardin Ligan on Medium]]></description>
        <link>https://medium.com/@bernardinligan?source=rss-d2d7deb4533b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*weOv9uualwaGfdpcyw8LaQ.png</url>
            <title>Stories by Bernardin Ligan on Medium</title>
            <link>https://medium.com/@bernardinligan?source=rss-d2d7deb4533b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:52:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bernardinligan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Model to Map: Automating Land Use Classification with Vision Transformers, Google Earth Engine…]]></title>
            <link>https://medium.com/@bernardinligan/from-model-to-map-automating-land-use-classification-with-vision-transformers-and-google-earth-9a5510215054?source=rss-d2d7deb4533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5510215054</guid>
            <category><![CDATA[sentinel-2]]></category>
            <category><![CDATA[folium-map]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Bernardin Ligan]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 23:02:18 GMT</pubDate>
            <atom:updated>2025-09-23T16:33:09.309Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Model to Map: Automating Land Use Classification with Vision Transformers, Google Earth Engine and Folium</strong></h3><p>In <a href="https://medium.com/@bernardinligan/how-i-rebuilt-my-first-lulc-project-with-a-vision-transformer-and-clean-code-aa9a06094c89"><strong>Part 1</strong></a> (published in August), we built and trained a Vision Transformer (ViT) to classify land use and land cover (LULC) on the EuroSAT dataset — using clean code, modular design, and transfer learning.</p><p><strong>In Part 2</strong>, we’ll take that trained model and deploy it to classify a real-world region, generating a full LULC map from Sentinel-2 imagery. This step is the natural next phase after model development: turning a trained AI into actionable insights for environmental monitoring, urban planning, or agricultural analysis.</p><h3><strong>1. Choosing a Region of Interest</strong></h3><p>The fact that our model was trained with EuroSAT data implies it will perform best in European regions. This reflects a well-known challenge in AI for remote sensing: <strong>domain shift</strong>. Models trained on data from one geographic region often struggle when applied to areas with different environmental conditions, land cover distributions, or even seasonal variations. Factors like lighting, vegetation types, and urban layouts can vary significantly, leading to reduced accuracy if the model hasn’t been exposed to similar patterns during training.</p><p>For this tutorial, we selected the <a href="https://en.wikipedia.org/wiki/Flevoland"><strong>Flevoland region</strong></a> in the Netherlands. Flevoland is a unique and compelling choice for several reasons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsMdx1782a0TyhiTVHUsFQ.jpeg" /><figcaption><a href="https://ontheworldmap.com/netherlands/province/flevoland/flevoland-location-on-the-netherlands-map.html">Flevoland location on the Netherlands map</a></figcaption></figure><ul><li><strong>Location</strong>: Situated in the central Netherlands, Flevoland is a <strong>reclaimed </strong><a href="https://en.wikipedia.org/wiki/Polder"><strong>polder</strong></a>, meaning it was created by draining water from the IJsselmeer lake. This makes it one of the youngest provinces in the country, with a landscape shaped by both human engineering and natural processes.</li><li><strong>Diversity of Land Use</strong>: Flevoland features a rich mix of agricultural fields, urban areas, forests, water bodies, and infrastructure. This diversity provides an excellent testbed for evaluating the model’s ability to distinguish between different land cover classes in a real-world setting.</li><li><strong>Data Availability</strong>: As part of the Netherlands, Flevoland benefits from high-quality, open-access satellite imagery (e.g., Sentinel-2), making it ideal for demonstration purposes.</li></ul><h3>2. <strong>Setting Up the Environment</strong></h3><h4>a. Importing Essential Libraries</h4><p>To automate the generation of Land Use/Land Cover (LULC) maps, we rely on a combination of geospatial, deep learning, and visualization libraries. Here’s a breakdown of their roles:</p><ul><li><strong>eeconvert</strong>: A utility library for converting between GeoJSON and Google Earth Engine (GEE) feature collections, simplifying the integration of vector data with GEE.</li><li><strong>geopandas</strong>: Extends the capabilities of pandas to handle geospatial data, allowing us to work with geometries (e.g., polygons, points) and perform spatial operations.</li><li><strong>shapely</strong>: A library for manipulation and analysis of planar geometric objects (e.g., polygons, lines). It’s often used alongside geopandas for geometric operations.</li><li><strong>rasterio</strong>: A powerful library for working with geospatial raster data (e.g., satellite imagery). It enables reading, writing, and processing raster files, as well as masking and cropping operations.</li><li><strong>folium</strong>: A Python library for creating interactive maps. It’s built on Leaflet.js and allows us to visualize geospatial data in an interactive web map format.</li><li><strong>geemap</strong>: A Python package for interactive mapping with Google Earth Engine. It simplifies the process of visualizing and analyzing GEE data by integrating with folium and ipyleaflet.</li><li><strong>geojson</strong>: A library for working with GeoJSON data, a standard format for encoding geographic data structures. It’s used to serialize and deserialize GeoJSON objects.</li><li><strong>torch</strong>: PyTorch, the deep learning framework we use to load our pre-trained Vision Transformer (ViT) model and perform inference on the satellite imagery.</li><li>etc</li></ul><h4>b. Authenticating Google Earth Engine</h4><p>Google Earth Engine (GEE) is a cloud-based platform for planetary-scale geospatial analysis. To access its vast repository of satellite imagery and geospatial datasets, you’ll need to authenticate your account.</p><p><strong>Steps to Authenticate:</strong></p><ul><li><strong>Sign Up for Access</strong>: If you haven’t already, request access to Google Earth Engine by visiting <a href="https://signup.earthengine.google.com/#!/">https://signup.earthengine.google.com/</a>. Approval typically takes a few days.</li><li><strong>Access the GEE Code Editor</strong>: Once approved, you can access the GEE platform at <a href="https://code.earthengine.google.com/">https://code.earthengine.google.com/</a>.</li><li><strong>Authenticate in Python</strong>: In your Python environment, run the following commands to authenticate and initialize the Earth Engine API:</li></ul><pre>import ee<br>ee.Authenticate()  # Follow the prompts to authenticate via your Google account.<br>ee.Initialize()    # Initializes the Earth Engine API.</pre><ul><li><strong>`ee.Authenticate()` </strong>opens a browser window where you can log in with your Google account and grant the necessary permissions.</li><li><strong>`ee.Initialize()` </strong>sets up the Earth Engine environment in your Python session, allowing you to interact with GEE’s datasets and tools.</li></ul><h3>3. <strong>Downloading Country Boundaries</strong></h3><p>To download administrative boundaries, we use the <strong>geoBoundaries API</strong>, a free and open database of global political boundaries. The API request follows a simple pattern:</p><pre>ISO = &#39;NLD&#39;      # 3-letter ISO country code (e.g., &#39;NLD&#39; for Netherlands)<br>ADM = &#39;ADM1&#39;     # Administrative level (e.g., &#39;ADM1&#39; for provinces/states)<br>api_url = f&quot;https://www.geoboundaries.org/api/current/gbOpen/{ISO}/{ADM}/</pre><ul><li><strong>ISO</strong>: A 3-letter code representing the country, based on the <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3">ISO 3166–1 alpha-3 standard</a>. For example, &#39;NLD&#39; for the Netherlands.</li><li><strong>ADM</strong>: Specifies the administrative level of the boundaries. Common values include:</li><li>ADM0: Country-level boundaries.</li><li>ADM1: First-level administrative divisions (e.g., provinces, states).</li><li>ADM2: Second-level divisions (e.g., counties, districts).</li><li>…</li></ul><p>The API returns a JSON response containing metadata and download links for the requested boundaries.</p><pre>start = time.time()<br>r = requests.get(api_url)<br><br>r.raise_for_status()<br>data = r.json()<br>assert len(data) &gt; 0, &quot;No boundaries returned!&quot;</pre><p>After making the request, the response (data) is a dictionary with metadata about the boundaries. One of the key elements is:</p><pre>&#39;gjDownloadURL&#39;: &#39;https://github.com/wmgeolab/geoBoundaries/raw/9469f09/releaseData/gbOpen/NLD/ADM1/geoBoundaries-NLD-ADM1.geojson&#39;</pre><p>This URL provides direct access to the <strong>GeoJSON file</strong> containing all ADM1 boundaries for the Netherlands.</p><p>We use the gjDownloadURL to fetch and save the GeoJSON data locally:</p><pre>dl_url = data[&#39;gjDownloadURL&#39;]<br>print(&quot;GeoJSON URL:&quot;, dl_url)# Download and save the GeoJSON file<br>filename = &#39;geoboundary.geojson&#39;<br>geojson_data = requests.get(dl_url).json()with open(filename, &#39;w&#39;) as f:<br>    <br>geojson.dump(geojson_data, f)print(&quot;Saved to&quot;, filename)<br><br># Load in GeoPandas<br>gdf = gpd.read_file(filename)<br>print(&quot;Data dimensions:&quot;, gdf.shape)<br>gdf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*ncWskoIBmCDz5tvJHUeywg.png" /><figcaption>Geopandas Dataframe of all ADM1 of Netherlands</figcaption></figure><p>To visualize the boundary for Flevoland, we filter the geodataframe to focus on the <strong>Flevoland</strong> province.</p><pre><br>shape_name = &#39;Flevoland&#39;<br>fig, ax = plt.subplots(1, figsize=(10, 10))<br>gdf[gdf.shapeName == shape_name].plot(&#39;shapeName&#39;, legend=True, ax=ax);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*aIoAGhXHDcMSSIMOhtESXA.png" /><figcaption>Flevoland Boundary</figcaption></figure><h3><strong>4. Generating Sentinel-2 Satellite Images for Flevoland</strong></h3><p><strong>Sentinel-2</strong> is a European Earth observation mission that provides high-resolution, multispectral imagery globally. It captures <strong>13 spectral bands</strong> at varying resolutions (10m, 20m, and 60m), including visible, near-infrared, and shortwave infrared bands. For this tutorial, we focus <strong>only on the RGB bands</strong> — red (B4), green (B3), and blue (B2) — to align with the input requirements of our pre-trained Vision Transformer (ViT) model.</p><p>To generate a cloud-free, median-aggregated Sentinel-2 image for Flevoland, we use the generate_image function from utils2.py. This function leverages the <strong>Google Earth Engine (GEE) API</strong> to:</p><ul><li>Filter images by region, date range, and cloud cover.</li><li>Compute the median of all qualifying images to reduce noise and cloud contamination.</li><li>Extract the RGB bands (B4, B3, B2) for visualization and analysis.\</li></ul><pre>from utils2 import generate_image# Get the shape geometry for Flevoland<br><br>region = gdf.loc[gdf.shapeName == shape_name]<br>centroid = region.iloc[0].geometry.centroid.coords[0]<br>region = eec.gdfToFc(region)  # Convert GeoDataFrame to GEE FeatureCollection<br><br># Generate RGB image using GEE<br>image = generate_image(<br>    region,<br>    product=&#39;COPERNICUS/S2_SR_HARMONIZED&#39;,  # Harmonized Sentinel-2 dataset<br>    min_date=&#39;2021-01-01&#39;,  # Start date for image collection<br>    max_date=&#39;2021-12-31&#39;,  # End date for image collection<br>    cloud_pct=10,  # Filter images with &lt;10% cloud cover<br>)<br><br># Visualize the map<br>Map = geemap.Map(center=[centroid[1], centroid[0]], zoom=10)<br>Map.addLayer(image, {}, &#39;S2_SR_HARMONIZED&#39;)<br>Map.addLayerControl()</pre><p>This code fetches all Sentinel-2 images for Flevoland in 2021, filters out images with high cloud cover, computes the median composite, and visualizes the result using geemap.</p><p>To facilitate further processing, we export the generated image to Google Drive as a <strong>GeoTIFF</strong> file:</p><pre>folder = &#39;Colab Notebooks&#39;  # Destination folder in Google Drive<br>task = export_image(image, shape_name, region, folder)</pre><p>The export_image function (also in utils2.py) handles the export process, saving the image as Flevoland.tif.</p><p>After exporting, we download the image locally and visualize it using rasterio and geopandas</p><pre># Define the local path for the image<br>inference_path = &#39;./data/Inference/&#39;<br>tif_file = inference_path + &#39;{}.tif&#39;.format(shape_name)<br><br># Open the image using Rasterio<br>image = rio.open(tif_file)<br>boundary = gdf[gdf.shapeName == shape_name]<br><br># Plot the image with the boundary overlay<br>fig, ax = plt.subplots(figsize=(15, 15))<br>boundary.plot(facecolor=&quot;none&quot;, edgecolor=&#39;red&#39;, ax=ax)<br>show(image, ax=ax);</pre><p>This code loads the GeoTIFF file using rasterio, overlays the administrative boundary of Flevoland (in red) on the satellite image and displays the result, showing the region’s land cover in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGYt1rMZ-EChSE9NorvwAA.png" /><figcaption><em>Sentinel-2 RGB composite of Flevoland, Netherlands (2021), with administrative boundaries overlaid in red.</em></figcaption></figure><h3>5. <strong>Generating 64x64 px GeoJSON Tiles</strong></h3><h4>Why 64x64 Pixels?</h4><p>In the previous tutorial, we trained our deep learning model on the <strong>EuroSAT RGB dataset</strong>, which consists of <strong>64x64 pixel Sentinel-2 image patches</strong>. To ensure compatibility with our pre-trained Vision Transformer (ViT) model, we need to break down our large Sentinel-2 image of Flevoland into smaller <strong>64x64 pixel tiles</strong>.</p><p>We use the generate_tiles function from utils2.py to create a grid of 64x64 pixel polygons across the Flevoland Sentinel-2 image. This function leverages <strong>Rasterio&#39;s window utilities</strong> to systematically divide the image into tiles and save them as a <strong>GeoJSON file</strong>.</p><pre>output_file = inference_path + &#39;{}.geojson&#39;.format(shape_name)<br>tiles = generate_tiles(tif_file, output_file, shape_name, size=64)<br>print(&#39;Data dimensions: {}&#39;.format(tiles.shape))<br>tiles.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*H73DiaMTMCux5FrNd9aUTw.png" /></figure><p>To ensure the tiles are correctly generated, we visualize them overlaid on the Sentinel-2 image:</p><pre>image = rio.open(tif_file)<br>fig, ax = plt.subplots(figsize=(15, 15))<br>tiles.plot(facecolor=&quot;none&quot;, edgecolor=&#39;red&#39;, ax=ax)<br>show(image, ax=ax);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zD6_lXCISrNomKfIfDtTTg.png" /></figure><p>The polygons are generated for <strong>all regions</strong>, including empty (black) areas outside Flevoland. Predicting land cover for these blank regions would be computationally inefficient and unnecessary.</p><p>To address this, we use <strong>GeoPandas’ </strong><strong>sjoin function</strong> to retain only the tiles that lie <strong>within the Flevoland boundary</strong>. This ensures we focus our analysis on relevant areas:</p><pre>tiles = gpd.sjoin(tiles, boundary, predicate=&#39;within&#39;)<br>fig, ax = plt.subplots(figsize=(15, 15))<br>tiles.plot(facecolor=&quot;none&quot;, edgecolor=&#39;red&#39;, ax=ax)<br>show(image, ax=ax);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTNq1E7bQu_s0TtKRbLcmA.png" /></figure><p>We can also visualize a single 64x64 pixel tile using the show_crop function:</p><pre>tile_id = 1  # Change the tile_id to visualize a different tile<br>show_crop(tif_file, [tiles.iloc[tile_id][&#39;geometry&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*p4SUcIiEkjOps90U4WPmTw.png" /></figure><h3>6. <strong>Generating the Land Use and Land Cover (LULC) Map</strong></h3><p>We begin by loading the <strong>pre-trained Vision Transformer (ViT) model</strong>, which was trained on the EuroSAT dataset. The EuroSAT dataset includes <strong>10 distinct LULC classes</strong>:</p><pre>classes = [<br>  &#39;AnnualCrop&#39;, &#39;Forest&#39;, &#39;HerbaceousVegetation&#39;, &#39;Highway&#39;,<br>  &#39;Industrial&#39;, &#39;Pasture&#39;, &#39;PermanentCrop&#39;, &#39;Residential&#39;,<br>  &#39;River&#39;, &#39;SeaLake&#39;<br>]</pre><p>The model is loaded using PyTorch, ensuring compatibility with the Vision Transformer architecture:</p><pre>import torch<br>from torchvision import models<br><br>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>model_file = &#39;./outputs/best_model.pth&#39;<br>torch.serialization.add_safe_globals([models.vision_transformer.VisionTransformer])<br>model = torch.load(model_file, map_location=device, weights_only=False)<br>model.eval()</pre><p>Before running inference, we apply the same <strong>data transformations</strong> used during training to ensure consistency. This includes resizing, center cropping, and normalization:</p><pre>imagenet_mean, imagenet_std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]<br><br>transform = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(imagenet_mean, imagenet_std)<br>])</pre><p>To efficiently process the 64x64 pixel tiles, we create a <strong>custom </strong><strong>TileDataset class</strong> and a <strong>PyTorch </strong><strong>DataLoader</strong>. This approach offers several advantages over a simple loop:</p><ul><li><strong>Batching</strong>: Processes multiple tiles simultaneously, leveraging GPU parallelism.</li><li><strong>Memory Efficiency</strong>: Loads and transforms tiles on-the-fly, reducing memory overhead.</li><li><strong>Multi-Processing</strong>: Uses multiple CPU workers to speed up data loading.</li></ul><p>The TileDataset class dynamically crops tiles from the raster image and applies the required transformations:</p><pre>from torch.utils.data import Dataset, DataLoader<br>from rasterio.mask import mask<br><br><br>class TileDataset(Dataset):<br>    def __init__(self, image_path, geoms, transform=None):<br>        self.image_path = image_path<br>        self.geoms = geoms<br>        self.transform = transform    <br><br>    def __len__(self):<br>        return len(self.geoms)    <br><br>    def __getitem__(self, idx):<br>        geom = [self.geoms[idx]]<br><br>        with rio.open(self.image_path) as src:<br>            out_image, _ = mask(src, geom, crop=True)<br>        _, x_nonzero, y_nonzero = np.nonzero(out_image)<br>        <br>        out_image = out_image[<br>            :, np.min(x_nonzero):np.max(x_nonzero),<br>            np.min(y_nonzero):np.max(y_nonzero)<br>        ]<br>        <br>        out_image = np.moveaxis(out_image, 0, -1).astype(np.uint8)<br>        img = Image.fromarray(out_image)<br>        <br>        if self.transform:<br>            img = self.transform(img)<br><br>        return img, idx<br><br># Create dataset and DataLoader<br>dataset = TileDataset(tif_file, tiles.geometry, transform=transform)<br>loader = DataLoader(dataset, batch_size=64, shuffle=False, num_workers=8)<br></pre><p>We perform inference using the DataLoader to process batches of tiles efficiently. The model predicts the LULC class for each tile, and we map the predictions back to their corresponding class labels:</p><pre>all_preds = []<br>model.eval()<br>device = next(model.parameters()).device<br>with torch.no_grad():<br>    for imgs, idxs in loader:<br>        imgs = imgs.to(device)<br>        outputs = model(imgs)<br>        preds = outputs.argmax(dim=1).cpu().numpy()<br>        all_preds.extend(preds)<br>labels = [classes[p] for p in all_preds]<br>tiles[&#39;pred&#39;] = labels</pre><p>The predictions are saved as a <strong>GeoJSON file</strong>, preserving the spatial information and predicted LULC classes for each tile:</p><pre>output_path = &#39;./outputs/{}_preds.geojson&#39;.format(shape_name)<br>tiles.to_file(output_path, driver=&quot;GeoJSON&quot;)</pre><p>To create an <strong>interactive map</strong>, we use <strong>Folium</strong> to overlay the predicted LULC classes on a satellite basemap. Each class is assigned a distinct color for clarity:</p><pre>colors = {<br>  &#39;AnnualCrop&#39;: &#39;lightgreen&#39;, &#39;Forest&#39;: &#39;forestgreen&#39;,<br>  &#39;HerbaceousVegetation&#39;: &#39;yellowgreen&#39;, &#39;Highway&#39;: &#39;gray&#39;,<br>  &#39;Industrial&#39;: &#39;red&#39;, &#39;Pasture&#39;: &#39;mediumseagreen&#39;,<br>  &#39;PermanentCrop&#39;: &#39;chartreuse&#39;, &#39;Residential&#39;: &#39;magenta&#39;,<br>  &#39;River&#39;: &#39;dodgerblue&#39;, &#39;SeaLake&#39;: &#39;blue&#39;<br>}<br><br>tiles[&#39;color&#39;] = tiles[&quot;pred&quot;].apply(lambda x: cl.to_hex(colors.get(x)))<br><br># Load predictions<br>filepath = &#39;./outputs/{}_preds.geojson&#39;.format(shape_name)<br>tiles = gpd.read_file(filepath)<br><br># Create and customize the Folium map<br>map = folium.Map(location=[centroid[1], centroid[0]], zoom_start=10)<br>folium.TileLayer(<br>    tiles=&#39;https://mt1.google.com/vt/lyrs=s&amp;x={x}&amp;y={y}&amp;z={z}&#39;,<br>    attr=&#39;Google&#39;,<br>    name=&#39;Google Satellite&#39;,<br>    overlay=True,<br>    control=True<br>).add_to(map)<br><br># Add LULC layers with legend<br>legend_txt = &#39;&lt;span style=&quot;color: {col};&quot;&gt;{txt}&lt;/span&gt;&#39;<br>for label, color in colors.items():<br>    name = legend_txt.format(txt=label, col=color)<br>    feat_group = folium.FeatureGroup(name=name)<br>    subtiles = tiles[tiles.pred == label]<br>    if len(subtiles) &gt; 0:<br>        folium.GeoJson(<br>            subtiles,<br>            style_function=lambda feature: {<br>                &#39;fillColor&#39;: feature[&#39;properties&#39;][&#39;color&#39;],<br>                &#39;color&#39;: &#39;black&#39;,<br>                &#39;weight&#39;: 1,<br>                &#39;fillOpacity&#39;: 0.5,<br>            },<br>            name=&#39;LULC Map&#39;<br>        ).add_to(feat_group)<br>    map.add_child(feat_group)<br>folium.LayerControl().add_to(map)<br>map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPdb56dCjIibi3Oimlvjyw.png" /></figure><p>Finally, the interactive map is saved as both an <strong>HTML file</strong> for web viewing and a <strong>PNG image</strong> for easy sharing:</p><pre>map.save(&quot;./outputs/lulc_map_flevoland.html&quot;)<br><br>print(&quot;✅ Map saved as ./outputs/lulc_map_flevoland.html&quot;)from html2image import Html2Image<br><br>hti = Html2Image()<br>hti.screenshot(<br>    html_file=&quot;./outputs/lulc_map_flevoland.html&quot;,<br>    save_as=&quot;lulc_map_flevoland.png&quot;,<br>    size=(1200, 800)<br>)<br>print(&quot;✅ Map saved as lulc_map_flevoland.png&quot;)</pre><p>With the LULC map now generated and visualized, you can explore the results interactively or use them for further analysis!</p><h3>Conclusion</h3><p>In this tutorial, we deployed a Vision Transformer (ViT) model to generate <strong>Land Use/Land Cover (LULC) maps</strong> from Sentinel-2 imagery, creating a fully automated pipeline from data to insights. To extend this project, consider building a <strong>Streamlit dashboard</strong> where users can upload their own regions of interest (e.g., as Shapefiles) and visualize results interactively — no coding required.</p><p><strong>Find the complete codebase on my GitHub:</strong> 🔗 <a href="https://github.com/LiganiumInc/LULC-ViT-EuroSAT3B">LiganiumInc/LULC-ViT-EuroSAT3B</a></p><p>Let’s make geospatial AI accessible to everyone! 🚀</p><h3>References :</h3><ul><li><a href="https://colab.research.google.com/github/climatechange-ai-tutorials/lulc-classification/blob/main/land_use_land_cover_part2.ipynb">Land Use and Land Cover (LULC) Classification Using Deep Learning: Part 2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5510215054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Rebuilt My First LULC Project with a Vision Transformer and Clean Code]]></title>
            <link>https://medium.com/@bernardinligan/how-i-rebuilt-my-first-lulc-project-with-a-vision-transformer-and-clean-code-aa9a06094c89?source=rss-d2d7deb4533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9a06094c89</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[remote-sensing]]></category>
            <dc:creator><![CDATA[Bernardin Ligan]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 07:43:03 GMT</pubDate>
            <atom:updated>2025-07-16T07:43:03.067Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>🚀 1. From Summer School Curiosity to Structured Deep Learning Practice</strong></h3><p>Three years ago, I attended the <a href="https://www.climatechange.ai/events/summer_school2023">Climate Change AI Summer School</a>, a transformative learning experience that opened my eyes to the intersection of artificial intelligence and Earth observation. I was introduced for the first time to land use and land cover (LULC) classification.<br>The task was simple in spirit but powerful in implication: given satellite images, could a neural network learn to recognize landscapes like forests, rivers, cities, and farmland? We used a pre-trained ResNet-50 CNN on the EuroSAT dataset, and seeing it map the Earth’s surface with such precision truly amazed me 🌍.<br>That tutorial planted a seed. Over the years, as I grew more experienced in deep learning and geospatial analysis, I found myself wanting to return to the problem — but this time, with a more structured, production-ready approach. I wanted to:</p><ul><li>Rebuild the LULC pipeline using <strong>modular PyTorch code</strong> and configuration files</li><li>Manage environments more cleanly using <strong>Pipenv</strong> (instead of plain requirements.txt)</li><li>Swap out the traditional CNN for something more modern and scalable: the <strong>Vision Transformer (ViT)</strong> 🧠</li></ul><p>In this blog post, I’ll walk you through how I revisited that early project — with cleaner code, stronger tooling, and a state-of-the-art model that redefines how we interpret images. But before we dive into the model architecture, let’s revisit why Land Use and Land Cover mapping is such a critical task in our climate-challenged world.</p><h3>🌍 <strong>2. Why Land Use and Land Cover Classification Matters</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHIxggYqCz2YOan9ZiiAIQ.png" /><figcaption><a href="https://www.impactobservatory.com/10m-land-cover/">https://www.impactobservatory.com/10m-land-cover/</a></figcaption></figure><p>Land Use and Land Cover (LULC) classification might sound technical, but its impact is easy to understand. It’s about knowing what’s on the Earth’s surface — from forests and rivers to urban areas and farmland. This kind of information is critical for:</p><ul><li>🛰 <strong>Monitoring environmental changes</strong>, like deforestation or urban sprawl</li><li>🏙 <strong>Planning smarter cities</strong> and infrastructure</li><li>🌾 <strong>Managing agriculture and food systems</strong></li><li>⚠️ <strong>Preparing for climate risks</strong>, such as floods or droughts</li></ul><p>Thanks to open satellite imagery like Sentinel-2 and datasets like EuroSAT, we can now train deep learning models to automatically map land cover at scale. In this project, I used the RGB version of EuroSAT, which contains over 27,000 labeled image patches across 10 land cover classes.</p><h3>🧱 3. Rebuilding the Project the Right Way: Pipenv, Configs, and Clean Code</h3><p>When I decided to revisit my first LULC classification project, I didn’t just want to change the model — I wanted to change the way I <em>build</em>.</p><p>Instead of keeping everything in a single notebook with hardcoded paths and random package versions, I took a more structured approach. Let me walk you through how I set up the project from scratch, with reproducibility and modularity in mind.</p><h4>🛠 Step 1 — Create a Project Folder and Use Pipenv</h4><p>I started by creating a dedicated folder for the project:</p><pre>mkdir LULC-ViT-EuroSAT3B<br>cd LULC-ViT-EuroSAT3B</pre><p>To manage the Python environment, I used <a href="https://pipenv.pypa.io/en/latest/"><strong>Pipenv</strong></a> instead of venv + requirements.txt. Why?</p><p>✅ It creates a clean virtual environment inside the project<br> ✅ It keeps track of installed packages with a Pipfile<br> ✅ It locks exact versions using Pipfile.lock, ensuring full reproducibility<br> ✅ It works like poetry-lite: simple, focused, and powerful</p><p>Install Pipenv (if needed):</p><pre>sudo apt install pipenv</pre><p>Then create your environment:</p><pre>export PIPENV_VENV_IN_PROJECT=1  # store the venv inside the project folder<br>pipenv install<br>pipenv shell</pre><p>Now you’re inside a fully isolated environment. You can install packages like this:</p><pre>pipenv install torch torchvision<br>pipenv install numpy matplotlib pandas seaborn pillow tqdm torchinfo pyyaml</pre><p>Each command updates your Pipfile and locks the versions in Pipfile.lock. This way, anyone can recreate your exact environment with just:</p><pre>pipenv install --dev</pre><h4>🌍 Step 2 — Download and Organize the Dataset</h4><p>I used the RGB version of the <a href="https://github.com/phelber/EuroSAT">EuroSAT dataset</a>, which contains 27,000 satellite image patches across 10 land cover categories.</p><p>After downloading and unzipping, I placed it in a data/ folder like this:</p><pre>mkdir -p data/EuroSAT/<br># Move the extracted &quot;2750&quot; folder inside<br>mv EuroSAT_RGB/2750 data/EuroSAT/</pre><h4>⚙️ Step 3 — Add a Configuration File</h4><p>Next, I created a config.yaml file to store all important settings. This makes it easy to adjust parameters without changing any code.</p><p><strong>📄 </strong><strong>config.yaml</strong></p><pre># General settings<br>dataset_name: &quot;EuroSAT&quot;<br>data_dir: &quot;./data/EuroSAT/2750/&quot;<br>save_path: &quot;./outputs/&quot;<br>seed: 42<br><br># Split settings<br>num_classes: 10<br>train_ratio: 0.8<br>val_ratio: 0.2<br>percentage_per_class: 0.3<br><br># Training settings<br>batch_size: 32<br>num_epochs: 10<br>lr: 0.001<br>weight_decay: 0.05<br><br># Learning rate scheduler<br>use_scheduler: false</pre><p><strong>Explanation:</strong></p><ul><li>dataset_name: just for logging</li><li>data_dir: where the dataset is stored</li><li>save_path: where to store outputs (models, plots)</li><li>seed: for reproducibility</li><li>train_ratio, val_ratio, percentage_per_class: how the dataset is split and sampled</li><li>batch_size, num_epochs, lr, weight_decay: training hyperparameters</li><li>use_scheduler: flag to activate learning rate scheduling</li></ul><h4>📓 Step 4 — Create the Notebook and Load Configs</h4><p>Now I created a notebook named LULC_3BIMG_VIT.ipynb and started it with a clean configuration load:</p><pre>import os<br>import yaml<br>import torch<br>import numpy as np<br>from utils import set_seeds  <br><br><br># Load config<br>cfg_path = &quot;config.yaml&quot;<br>with open(cfg_path) as f:<br>    config = yaml.safe_load(f)<br># Print config for inspection<br>print(config)<br># Create output directory<br>SAVE_PATH = config[&#39;save_path&#39;]<br>if not os.path.exists(SAVE_PATH):<br>    os.makedirs(SAVE_PATH)<br># Reproducibility<br>set_seeds(seed=config[&#39;seed&#39;])<br># Runtime info<br>NUM_WORKERS = os.cpu_count()<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>print(f&quot;Seed: {config[&#39;seed&#39;]}&quot;)<br>print(f&quot;Number of workers: {NUM_WORKERS}&quot;)<br>print(f&quot;Device: {device}&quot;)<br>if device == &quot;cuda&quot;:<br>    print(f&quot;GPU: {torch.cuda.get_device_name(0)}&quot;)</pre><p><strong>Sample output:</strong></p><pre>Seed: 42<br>Number of workers: 16<br>Device: cuda<br>GPU: NVIDIA GeForce RTX 4060 Laptop GPU</pre><h4>🧩 Step 5 — Set Up the Code Modules</h4><p>To keep things modular and readable, I created three Python files:</p><h4>📁 datafactory.py</h4><ul><li>Contains the image transformations and the EuroSAT dataset wrapper.</li></ul><h4>📁 engine.py</h4><ul><li>Handles model training and validation steps.</li></ul><h4>📁 utils.py</h4><ul><li>Houses helper functions like setting random seeds, sampling subsets, and running predictions.</li></ul><p>Each file focuses on <strong>one clear responsibility</strong>, which makes the entire codebase easier to scale, debug, and maintain.</p><h4>🗂️ Final Project Structure (So Far)</h4><pre>LULC-ViT-EuroSAT3B/<br>├── config.yaml<br>├── data/<br>│   └── EuroSAT/2750/<br>├── datafactory.py<br>├── engine.py<br>├── utils.py<br>├── LULC_3BIMG_VIT.ipynb<br>├── outputs/<br>├── Pipfile<br>└── Pipfile.lock</pre><p>At this point, I had a solid foundation: a clean environment, modular code, and all configs separated from logic.</p><h3>🧪 4. Preparing the Data: Transform, Split, and Load</h3><p>With the environment ready and the project structure in place, the next step was handling the data.</p><h4>🗂 Dataset Structure</h4><p>After downloading and extracting the RGB version of EuroSAT, I organized it inside the project’s data/ folder:</p><pre>├── data<br>│   └── EuroSAT<br>│       └── 2750<br>│           ├── AnnualCrop<br>│           ├── Forest<br>│           ├── HerbaceousVegetation<br>│           ├── Highway<br>│           ├── Industrial<br>│           ├── Pasture<br>│           ├── PermanentCrop<br>│           ├── Residential<br>│           ├── River<br>│           └── SeaLake</pre><p>Each subfolder represents a land cover class and contains hundreds of image patches (64×64 pixels each).</p><h4>🧪 Data Augmentation and Normalization</h4><p>To make the model generalize better, I applied data augmentation during training:</p><pre>from torchvision import transforms<br>input_size = 224<br>imagenet_mean, imagenet_std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]<br><br>train_transform = transforms.Compose([<br>    transforms.RandomResizedCrop(input_size),<br>    transforms.RandomHorizontalFlip(),<br>    transforms.RandomVerticalFlip(),<br>    transforms.ToTensor(),<br>    transforms.Normalize(imagenet_mean, imagenet_std)<br>])<br>test_transform = transforms.Compose([<br>    transforms.Resize(input_size),<br>    transforms.CenterCrop(input_size),<br>    transforms.ToTensor(),<br>    transforms.Normalize(imagenet_mean, imagenet_std)<br>])</pre><h4>🧱 Wrapping the Dataset</h4><p>To handle transformations dynamically, I wrapped the base dataset using a custom EuroSAT class:</p><pre>from torch.utils import data<br><br>class EuroSAT(data.Dataset):<br>    def __init__(self, dataset, transform=None):<br>        self.dataset = dataset<br>        self.transform = transform<br>    def __getitem__(self, index):<br>        x, y = self.dataset[index]<br>        if self.transform:<br>            x = self.transform(x)<br>        return x, y<br>    def __len__(self):<br>        return len(self.dataset)</pre><p>Now, instead of applying transforms manually, the EuroSAT class ensures they&#39;re applied on-the-fly as batches are loaded.</p><h4>🔍 Exploring the Dataset in the Notebook</h4><pre>from torchvision import datasets<br><br>data_dir = config[&#39;data_dir&#39;]<br>dataset = datasets.ImageFolder(data_dir)<br>class_names = dataset.classes<br><br>print(&quot;Class names:&quot;, class_names)<br>print(&quot;Total number of classes:&quot;, len(class_names))</pre><p><strong>Output:</strong></p><pre>Class names: [&#39;AnnualCrop&#39;, &#39;Forest&#39;, &#39;HerbaceousVegetation&#39;, &#39;Highway&#39;,<br>              &#39;Industrial&#39;, &#39;Pasture&#39;, &#39;PermanentCrop&#39;, &#39;Residential&#39;, &#39;River&#39;, &#39;SeaLake&#39;]<br>Total number of classes: 10</pre><p>I apply the appropriate transforms to create the training and test datasets:</p><pre>train_data = EuroSAT(dataset, train_transform)<br>test_data = EuroSAT(dataset, test_transform)</pre><h4>✂️ Splitting and Sampling the Data</h4><p>I first performed a standard 80/20 train/test split:</p><pre>from torch.utils import data<br>import numpy as np<br><br>train_size = config[&#39;train_ratio&#39;]<br>indices = list(range(len(dataset)))<br>np.random.shuffle(indices)<br>split = int(train_size * len(dataset))<br>train_data = data.Subset(train_data, indices[:split])<br>test_data = data.Subset(test_data, indices[split:])<br>print(&quot;Train/test sizes: {}/{}&quot;.format(len(train_data), len(test_data)))</pre><p><strong>Output:</strong><br> Train/test sizes: 21600/5400</p><p>To speed up experimentation, I sampled <strong>30% of each class</strong> from the training set:</p><pre>filtered_train_data = sample_subset_per_class(train_data, percentage=config[&#39;percentage_per_class&#39;])</pre><p>This balances the class distribution and drastically reduces training time during prototyping.</p><h4>🔀 Train/Validation Split</h4><p>From this filtered set, I created a validation split:</p><pre>val_split = config[&#39;val_ratio&#39;]<br>val_len = int(len(filtered_train_data) * val_split)<br>train_len = len(filtered_train_data) - val_len<br><br>from torch.utils.data import random_split<br>train_small, val_small = random_split(filtered_train_data, [train_len, val_len])<br>print(&quot;Train/val sizes: {}/{}&quot;.format(len(train_small), len(val_small)))</pre><p><strong>Output:</strong><br> Train/val sizes: 5180/1294</p><h4>📦 Loading the Data with PyTorch DataLoaders</h4><p>Using DataLoader helps us:</p><ul><li>Load batches efficiently (especially with multiple CPU workers)</li><li>Shuffle data for training</li><li>Avoid memory overflow by streaming data</li></ul><p>Here’s how I created the data loaders:</p><pre>from torch.utils.data import DataLoader<br><br>train_loader = DataLoader(train_small, batch_size=config[&#39;batch_size&#39;], shuffle=True, num_workers=NUM_WORKERS)<br>val_loader   = DataLoader(val_small, batch_size=config[&#39;batch_size&#39;], shuffle=False, num_workers=NUM_WORKERS)<br>test_loader  = DataLoader(test_data,  batch_size=config[&#39;batch_size&#39;], shuffle=False, num_workers=NUM_WORKERS)</pre><p><strong>Explanation of key arguments:</strong></p><ul><li>batch_size: number of samples per batch (from config)</li><li>shuffle: randomizes data order (useful only for training)</li><li>num_workers: number of subprocesses for loading data (based on CPU cores)</li></ul><p>To validate everything works:</p><pre>batchX0, batchy0 = next(iter(train_loader))<br>print(batchX0.shape, batchy0.shape)</pre><p><strong>Output:</strong></p><pre>torch.Size([32, 3, 224, 224]) torch.Size([32])</pre><p>This confirms we’re loading batches of 32 RGB images, each resized to 224×224—exactly what our Vision Transformer expects. Everything’s clean, consistent, and ready for model training.</p><h3>🧠 5. Introducing Vision Transformer</h3><p>While the original project used a ResNet-50 — a powerful convolutional neural network — this time I wanted to try something newer: the <strong>Vision Transformer (ViT)</strong>.</p><p>Unlike CNNs that rely on spatial hierarchies and local filters, ViTs <strong>treat an image as a sequence of patches</strong> and process them using self-attention, just like transformers in NLP. This allows the model to learn global relationships between parts of an image, not just local features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SoXHGxDPUqFQHFbJKYoVLg.png" /><figcaption>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Dosovitskiy,+A">Alexey Dosovitskiy</a> et al., <a href="https://arxiv.org/abs/2010.11929">https://arxiv.org/abs/2010.11929</a></figcaption></figure><h4>How It Works</h4><p>Here’s the basic idea:</p><ol><li><strong>Split</strong> the image into patches (e.g., 16×16)</li><li><strong>Flatten and embed</strong> each patch into a vector</li><li><strong>Add positional encodings</strong></li><li><strong>Pass through transformer encoder blocks</strong></li><li>Use the output token to <strong>predict the class</strong></li></ol><h4>Transfer Learning</h4><p>Training ViTs from scratch is compute-intensive. Instead, we use <strong>transfer learning</strong>: start with a ViT pretrained on ImageNet-21k and fine-tune it on EuroSAT. This gives us:</p><ul><li>Faster convergence</li><li>Better accuracy with less data</li><li>Robust learned representations from millions of natural images</li></ul><h4>Loading the ViT in PyTorch</h4><pre>import torch<br>from torchvision import models<br>from torchvision.models import ViT_B_16_Weights<br><br># Load pretrained ViT base model<br>weights = ViT_B_16_Weights.DEFAULT<br>model = models.vit_b_16(weights=weights)<br># Replace the classification head<br>model.heads.head = torch.nn.Linear(model.heads.head.in_features, len(dataset.classes))<br>model = model.to(device)</pre><p>ViT_B_16 stands for <strong>Base</strong> ViT model with <strong>16×16 patch size</strong></p><p>I replace the final classification head to output 10 land cover classes</p><h4>Model Summary</h4><pre>from torchinfo import summary<br>summary(model, input_size=batchX0.shape)</pre><p><strong>Sample Output Highlights:</strong></p><pre>===============================================================================================<br>Layer (type:depth-idx)                        Output Shape              Param #<br>===============================================================================================<br>VisionTransformer                             [32, 10]                  768<br>├─Conv2d: 1-1                                 [32, 768, 14, 14]         590,592<br>├─Encoder: 1-2                                [32, 197, 768]            151,296<br>│    └─Dropout: 2-1                           [32, 197, 768]            --<br>│    └─Sequential: 2-2                        [32, 197, 768]            --<br>│    │    └─EncoderBlock: 3-1                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-2                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-3                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-4                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-5                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-6                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-7                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-8                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-9                 [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-10                [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-11                [32, 197, 768]            7,087,872<br>│    │    └─EncoderBlock: 3-12                [32, 197, 768]            7,087,872<br>│    └─LayerNorm: 2-3                         [32, 197, 768]            1,536<br>├─Sequential: 1-3                             [32, 10]                  --<br>│    └─Linear: 2-4                            [32, 10]                  7,690<br>===============================================================================================<br>Total params: 85,806,346<br>Trainable params: 85,806,346<br>Non-trainable params: 0<br>Total mult-adds (Units.GIGABYTES): 5.52<br>===============================================================================================<br>Input size (MB): 19.27<br>Forward/backward pass size (MB): 3330.74<br>Params size (MB): 229.22<br>Estimated Total Size (MB): 3579.23<br>==============================================================================================</pre><p>🔍 <strong>What does this tell us?</strong></p><ul><li>ViT is large — over <strong>85 million parameters</strong></li><li>The <strong>input</strong> goes through 12 encoder blocks</li><li>Each encoder block has multi-head self-attention, layer norms, and MLPs</li><li>The model expects inputs of shape [batch_size, 3, 224, 224]</li></ul><h4>Set Up the Loss and Optimizer</h4><pre>criterion = torch.nn.CrossEntropyLoss()<br>optimizer = torch.optim.SGD(model.parameters(), lr=config[&#39;lr&#39;])</pre><p>For this setup, <strong>SGD</strong> with a learning rate of 0.001 worked well. You could experiment with <strong>AdamW</strong> for potentially better results.</p><h3>6. Training the Model</h3><p>Now that everything is ready, we train the model using a clean modular pipeline. All training logic is abstracted into the engine.py file, which contains three functions:</p><ul><li>train_step(...) – Trains on a single epoch</li><li>val_step(...) – Evaluates on the validation set</li><li>train(...) – Manages the training loop, saves the best model</li></ul><h4>Launch Training</h4><pre>from timeit import default_timer as timer<br><br>best_name = SAVE_PATH + &quot;best_model.pth&quot;<br>start_time = timer()<br>results, best_model = train(<br>    model=model,<br>    train_dataloader=train_loader,<br>    val_dataloader=val_loader,<br>    optimizer=optimizer,<br>    loss_fn=criterion,<br>    device=device,<br>    epochs=config[&#39;num_epochs&#39;],<br>    model_save_path=best_name,<br>    use_scheduler=config[&#39;use_scheduler&#39;],<br>)<br>torch.cuda.synchronize()<br>end_time = timer()</pre><pre>🕒 <strong>Why </strong><strong>torch.cuda.synchronize()?</strong><br> To ensure all CUDA operations complete before measuring total training time—otherwise end_time might record too early.</pre><p>The training logs will output metrics like:</p><pre> 0%|          | 0/10 [00:00&lt;?, ?it/s]<br>Epoch: 1 | train_loss: 1.6412 | train_acc: 0.5459 | val_loss: 1.1480 | val_acc: 0.7446 | <br> 10%|█         | 1/10 [03:25&lt;30:50, 205.63s/it]<br>✅ Best model saved with accuracy: 0.7446<br>Epoch: 2 | train_loss: 0.9164 | train_acc: 0.7973 | val_loss: 0.7575 | val_acc: 0.8399 | <br> 20%|██        | 2/10 [06:57&lt;27:55, 209.48s/it]<br>...<br>Epoch: 9 | train_loss: 0.2748 | train_acc: 0.9229 | val_loss: 0.2712 | val_acc: 0.9192 | <br>100%|██████████| 10/10 [25:40&lt;00:00, 154.08s/it]<br>Epoch: 10 | train_loss: 0.2443 | train_acc: 0.9315 | val_loss: 0.2638 | val_acc: 0.9159 | <br>Loading the best model for further tasks...</pre><p>The model automatically saves the <strong>checkpoint with the highest validation accuracy</strong>.</p><h3>📊 7. Visualizing Training and Making Predictions</h3><p>Once training was complete, it was time to evaluate how well the Vision Transformer actually performed.</p><h4>Tracking Accuracy and Loss</h4><p>The train(...) function automatically logs the metrics at each epoch in a dictionary:</p><pre>results = {<br>    &quot;train_loss&quot;: [],<br>    &quot;train_acc&quot;: [],<br>    &quot;val_loss&quot;: [],<br>    &quot;val_acc&quot;: [],<br>}</pre><p>You can quickly check how well the best model performed on the validation set:</p><pre>print(max(results[&#39;val_acc&#39;]))<br># Example: 0.9238</pre><h4>Plotting the Training Curves</h4><p>To better understand how training evolved over time, I used a simple helper function to visualize both loss and accuracy curves:</p><pre>def plot_loss_acc_curves(results, save_path, title):<br>    ...</pre><p>And used it like this:</p><pre>plot_loss_acc_curves(<br>    results, <br>    save_path=SAVE_PATH + &#39;loss_acc_curves.png&#39;, <br>    title=&quot;Loss and Accuracy Curves&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CECaEOIboLaNlh4TSi06CA.png" /><figcaption>Loss/Acc curves for training and validtion</figcaption></figure><p>This produces a side-by-side plot: one graph for <strong>loss</strong> and one for <strong>accuracy</strong>, across epochs.</p><h4>💾 Saving and Reloading the Model</h4><p>After training, I saved the best model checkpoint like this:</p><pre>model_file = SAVE_PATH + &quot;best_model.pth&quot;<br>torch.save(best_model, model_file)<br>print(f&quot;Model successfully saved to {model_file}&quot;)</pre><p>To reload it later (for inference or continued training):</p><pre>model = torch.load(model_file, weights_only=False)<br>model.eval()<br>print(f&quot;Model file {model_file} successfully loaded.&quot;)</pre><p>This makes it easy to deploy the model or reuse it across notebooks and scripts.</p><h4>🔍 Running Inference on a New Image</h4><p>To make predictions on individual images, I used the following utility:</p><pre>img_path = &#39;./data/EuroSAT/2750/Forest/Forest_1.jpg&#39;<br>predicted_class = predict_and_visualize(<br>    image_path=img_path,<br>    model=model,<br>    transform=test_transform,<br>    class_names=class_names,<br>    device=device<br>)</pre><h4>🔎 What predict_and_visualize Does</h4><p>Here’s how the function works under the hood:</p><pre>def predict_and_visualize(image_path, model, transform, class_names, device=&#39;cpu&#39;):<br>&quot;&quot;&quot;<br>    Predicts the class of an image using a trained model and visualizes it.<br><br>    Args:<br>        image_path (str): Path to the input image (PIL-compatible).<br>        model (torch.nn.Module): Trained PyTorch model for classification.<br>        transform (callable): Transformation function to preprocess the image.<br>        class_names (list): List of class names indexed by label.<br>        device (str): Device to run the model on (&#39;cpu&#39; or &#39;cuda&#39;).<br><br>    Returns:<br>        str: Predicted class label.<br>    &quot;&quot;&quot;<br>    # Load and transform image<br>    image = Image.open(image_path).convert(&quot;RGB&quot;)<br>    input_tensor = transform(image).unsqueeze(0).to(device)<br><br>    # Set model to eval mode and predict<br>    model.eval()<br>    with torch.no_grad():<br>        output = model(input_tensor)<br>        _, pred_idx = torch.max(output, 1)<br>        pred_label = class_names[pred_idx.item()]<br><br>    # Visualize<br>    fig, ax = plt.subplots(figsize=(4, 4))<br>    ax.imshow(image)<br>    ax.set_title(f&quot;Predicted class: {pred_label}&quot;)<br>    ax.axis(&#39;off&#39;)<br>    plt.show()<br><br>    return pred_label</pre><ul><li><strong>Loads the image</strong> using PIL</li><li><strong>Applies the same normalization and resizing</strong> as during training</li><li><strong>Feeds the image to the model</strong> in evaluation mode</li><li><strong>Extracts the predicted class index</strong></li><li><strong>Displays the image</strong> with its predicted label using matplotlib</li><li><strong>Returns the label</strong> as a string</li></ul><h3>✅ 8. Wrapping Up &amp; What’s Next</h3><p>Revisiting my early LULC classification project was more than just an upgrade in model architecture — it was a personal milestone. I went from experimenting in a single notebook to building a clean, modular deep learning pipeline powered by tools like:</p><ul><li>💼 <strong>Pipenv</strong> for environment management</li><li>🧱 <strong>Modular PyTorch code</strong> for better readability and reuse</li><li>🧠 <strong>Vision Transformers</strong> for powerful, context-aware image classification</li><li>📈 <strong>Simple yet effective visualizations</strong> for understanding model behavior</li><li>Find the complete code base on my github here : <a href="https://github.com/LiganiumInc/LULC-ViT-EuroSAT3B">https://github.com/LiganiumInc/LULC-ViT-EuroSAT3B</a></li></ul><h4>🔭 What’s Next: Real-World Inference on a Map</h4><p>In the next tutorial, we’ll <strong>take this model out of the lab and into the wild</strong>:</p><ul><li>We’ll choose a region in Europe using a polygon boundary (GeoJSON or Shapefile)</li><li>Split the region into image tiles</li><li>Use our trained ViT model to <strong>predict the land cover</strong> of each tile</li><li>And finally, <strong>visualize the results on an interactive map using Folium</strong> 🗺️</li></ul><blockquote><em>Imagine exploring a city or countryside and instantly seeing its predicted land use class, right from a web map — this is the next step toward real-world impact.</em></blockquote><h3>📚 References</h3><ul><li><a href="https://github.com/phelber/EuroSAT">EuroSAT Dataset — GitHub</a></li><li><a href="https://arxiv.org/abs/2010.11929">Vision Transformer (ViT) Paper — arXiv</a></li><li><a href="https://www.climatechange.ai/events/summer_school2023">Climate Change AI (CCAI) Summer School</a></li><li><a href="https://www.climatechange.ai/tutorials?search=id%3Aland-use-and-land-cover-lulc-classification-using-deep-learning-part-i">CCAI LULC Tutorial Part 1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9a06094c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free Offline Speech Recognition with Vosk]]></title>
            <link>https://medium.com/@bernardinligan/free-offline-speech-recognition-with-vosk-c3612bc9d98b?source=rss-d2d7deb4533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3612bc9d98b</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bernardin Ligan]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 23:17:05 GMT</pubDate>
            <atom:updated>2022-09-27T22:37:35.886Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comment utiliser la librairie Vosk pour la reconnaissance de la parole gratuitement et en mode offline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Enn6niVhNAz7PHKcZ180Cw.png" /><figcaption>Vosk Logo (Sinologic.net)</figcaption></figure><p>Le nombre d’applications embarquant des fonctionnalités de traitement de la voix grâce à l’intelligence artificielle (Speech Recognition, Speech to text, text to Speech etc ) a connu une explosion ces dernières années notamment avec l’essor des assistants virtuels tels que Google Assistant et Amazon Alexa et l’augmentation du nombre d’objets connectés.</p><p>Je travaille d’ailleurs actuellement sur un <a href="https://github.com/LiganiumInc/Mossaida">projet</a> destiné à aider les personnes à mobilité réduite à effectuer des tâches basiques sur un ordinateur grâce à leur voix. Bien qu’il existe de nombreuses librairies et API permettant de faire de la reconnaissance de la parole, je me suis vite confronté au tout début du projet à un problème : la plupart de ces outils exige une connexion à internet et présente des temps de latences lorsque cette dernière n’est pas de bonne qualité. Aussi le reste (les librairies ne nécessitant pas internet) pouvant fonctionner en mode offline ne fournissent pas toujours un résultat de bonne qualité.</p><p><strong><em>Quel outil utilisé alors pour du Speech Recognition de bonne qualité et en offline ?</em></strong></p><p>Après plusieurs recherches je suis tombé sur <strong><em>Vosk ,</em></strong> une boîte à outil Open Source de reconnaissance vocale développée par <strong>Alpha Cephei</strong>.</p><p>Elle supporte plus de 20 langues et dialectes (Anglais, anglais indien, allemand, français, espagnol, portugais, chinois, russe, turc, vietnamien, italien, néerlandais, catalan, arabe, grec, farsi, philippin, ukrainien, kazakh, suédois, japonais, espéranto, hindi, tchèque, polonais) et peut fonctionner en offline.</p><p>Par ailleurs elle est compatible avec de nombreux langages de programmation tels que C#, Java, Javascript etc et peut fonctionner sur des appareils légers comme Raspberry Pi, Android, iOS.</p><p>Voyons donc comment l’utiliser pour du Speech-to-text à travers le microphone de l’ordinateur.</p><h4><strong>Prérequis</strong></h4><ul><li>Installer et activer un environnement virtuel python</li></ul><blockquote>python3 -m venv env</blockquote><blockquote>source env/bin/activate</blockquote><ul><li>Installer les librairies portaudio et pyaudio qui sont utiles pour la manipulation du microphone</li></ul><blockquote>sudo apt-get install portaudio19-dev</blockquote><blockquote>pip install pyaudio</blockquote><ul><li>Installer Vosk</li></ul><blockquote>pip install vosk</blockquote><h4><strong>Speech to Text</strong></h4><p>Vosk dispose d’une liste de modèles pré-entraînés selon la langue que vous souhaitez utiliser. Allez sur le site <a href="https://alphacephei.com/vosk/models">suivant</a> et télécharger l’un des modèles disponible pour la langue française.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*bouQn4P4-ikyd2ovcGRg6Q.png" /><figcaption>List des modèles disponibles</figcaption></figure><p><strong>NB</strong> : Les modèles de grande taille ont de meilleurs performances mais l’inférence sera beaucoup plus longue avec ces derniers.</p><p>Ensuite décompressez le fichier télécharger dans votre répertoire de travail puis copiez le code suivant dans votre éditeur de texte.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93da56ca9ba16011d42644ed5ab187a4/href">https://medium.com/media/93da56ca9ba16011d42644ed5ab187a4/href</a></iframe><p>Dans le code on a instancié le modèle (changez le nom en fonction du fichier que vous avez téléchargé) puis ouvert un flux sur le microphone afin de pouvoir récupérer la voix en temps réel. Après le lancement du script, certaines configurations s’effectuent automatiquement dans le terminal puis le microphone passe en mode “On”. Dès que les configurations s’arrêtent dans le terminal, vous pouvez commencez à parler. Votre voix sera récupérée à travers le microphone et le modèle la convertira en texte. Le programme restera actif tant vous n’aurez pas dit “fin”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*zvapMPxynXMfDXQx3IDmKA.png" /></figure><h4>Conclusions</h4><p>Vosk est une bibliothèque open source de reconnaissance vocale dont le grand avantage par rapport à ses concurrents est sa capacité à fonctionner en offline avec des résultats acceptables. Cela pourrait être très utile si vous voulez créer une application embarquant la fonction de speech recognition à destination de personnes ayant accès à peu ou pas internet.</p><p>Si vous voulez aller plus loin, je vous invite à visiter ce <a href="https://github.com/LiganiumInc/Mossaida">projet</a> sur mon compte Github.</p><h4><strong>Merci de m’avoir lu !</strong></h4><ul><li>Si vous avez aimez l’article, suivez moi sur Medium pour plus de contenus relatifs à l’IA et la Data Science.</li><li>Vous pouvez également rejoindre mon réseau sur <a href="https://www.linkedin.com/in/bernardin-ligan/">Linkedin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3612bc9d98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>