Setting Up a Machine Learning Coding Environment with VS Code, Building an Image Classifier in VS Code

Why did we choose VS Code?

  • Powerful, versatile, and lightweight code editor
  • Supports a wide range of programming languages
  • Customizable options to enhance productivity
  • Ideal for developers at any skill level

Key features:

  • Intuitive and user-friendly interface
  • Intelligent code completion, syntax highlighting, and real-time error detection
  • Rich ecosystem of extensions for customization and extended functionality
  • Built-in Git integration for seamless version control
  • Cross-platform compatibility (Windows, macOS, and Linux)

If interested in other IDEs, reply with your request.




We will share a few demos shortly. Meanwhile, you can try out the tasks below:

  • Configuring VS Code for Python development
  • Using VS Code’s built-in Git version control features
  • Customizing VS Code’s theme and layout to suit your preferences
  • Leveraging VS Code’s debugging capabilities for Python

Let us know which demo you would find most interesting or helpful for your current projects. We want to make sure we cover the topics that are most relevant to you.

If you encounter any challenges or have questions, please feel free to share them with us. Your feedback will help us tailor the demos and provide targeted assistance. Looking forward to hearing from you and helping you get started with VS Code!

Step-by-step guide to get started

  1. Download VS Code:

    • Go to the official VS Code website: https://code.visualstudio.com/
    • Click on the “Download” button for your operating system (Windows, macOS, or Linux).
    • Wait for the download to complete.
  2. Install VS Code:

    • Locate the downloaded installation file and double-click on it.
    • Follow the installation wizard prompts to complete the installation process.
    • Once the installation is finished, launch VS Code.
  3. Familiarize yourself with the interface:

    • Take a moment to explore the VS Code interface and familiarize yourself with its layout.
    • The main areas include the Activity Bar on the left, the Editor in the center, and the Side Bar on the right.
  4. Install extensions (optional):

    • VS Code has a rich ecosystem of extensions that enhance its functionality and support various programming languages and frameworks.
    • Click on the Extensions icon in the Activity Bar (it looks like a square with four smaller squares).
    • Search for extensions relevant to your development needs (e.g., Python, JavaScript, HTML/CSS, etc.).
    • Click on the “Install” button for the desired extensions.

VS1


  1. Configure settings (optional):
    • VS Code allows you to customize various settings to suit your preferences.
    • Go to the File menu (Code menu on macOS) and select “Preferences” > “Settings”.
    • Explore the available settings and modify them as needed.
    • You can change themes, font size, tab size, and many other options.

VS2


  1. Set up version control (optional):

    • If you plan to use version control systems like Git, you can set up VS Code to work seamlessly with them.
    • Open the Command Palette by pressing Ctrl+Shift+P (or Cmd+Shift+P on macOS).
    • Type “Git” and select “Git: Initialize Repository” to initialize a Git repository in your project folder.
    • You can also clone existing repositories or connect to remote repositories.
  2. Start coding:

    • Create a new file or open an existing project.
    • Use the File menu or the keyboard shortcuts to create, open, and save files.
    • Take advantage of VS Code’s features like IntelliSense, code navigation, debugging, and built-in terminal.
  3. Customize your workspace (optional):

    • VS Code allows you to create and customize workspaces for different projects.
    • Go to the File menu and select “Add Folder to Workspace” to add project folders to your workspace.
    • You can also save your workspace configuration for future use.
  4. Explore additional features:

    • VS Code has many advanced features like code snippets, task automation, and remote development.
    • Explore the documentation and online resources to learn more about these features and how to leverage them in your development workflow.
  5. Keep VS Code updated:

    • VS Code regularly releases updates with new features, bug fixes, and performance improvements.
    • Go to the Help menu and select “Check for Updates” to ensure you have the latest version installed.

Remember, VS Code is highly customizable, and you can tailor it to your specific needs and preferences. Don’t hesitate to explore the settings, extensions, and features to create a personalized and efficient development environment.

Anaconda Details

Setup Without Anaconda
  1. Install Python:
  • Go to Download Python | Python.org
  • Download the latest version for your operating system
  • Run the installer, making sure to check “Add Python to PATH”
  1. Install Visual Studio Code:
  1. Set up Python in VS Code:
  • Open VS Code
  • Go to Extensions (Ctrl+Shift+X)
  • Search for “Python” and install the official Python extension
  1. Install required packages:
  • Open a terminal in VS Code (View > Terminal)
  • Run: pip install numpy pandas matplotlib scikit-learn
  1. Install GitHub Copilot:
  • In VS Code, go to Extensions again
  • Search for “GitHub Copilot” and install it
  • Follow the prompts to sign in to your GitHub account
Setup With Anaconda
  1. Install Anaconda:
  1. Install Visual Studio Code:
  1. Set up Anaconda in VS Code:
  • Open VS Code
  • Go to Extensions (Ctrl+Shift+X)
  • Search for and install:
    • “Python” extension
    • “Jupyter” extension
  1. Select Anaconda Python interpreter:
  • Open a Python file in VS Code
  • Click on the Python interpreter in the bottom status bar
  • Select the Anaconda Python interpreter from the list
  1. Create and activate an Anaconda environment (optional but recommended):
  • Open an Anaconda Prompt or terminal
  • Run: conda create --name myenv python=3.8
  • Activate it: conda activate myenv
  • In VS Code, select this new environment as your Python interpreter
  1. Install additional packages (if needed):
  • In the Anaconda Prompt with your environment activated, run: conda install numpy pandas matplotlib scikit-learn
  1. Install GitHub Copilot:
  • In VS Code, go to Extensions
  • Search for “GitHub Copilot” and install it
  • Follow the prompts to sign in to your GitHub account

Both options will give you a fully functional environment for Python development with VS Code and GitHub Copilot. The Anaconda option provides a more comprehensive scientific Python distribution out of the box, while the non-Anaconda option gives you more control over your Python installation.

Here’s a step-by-step guide to create this demo in VS Code:

1. Set Up Your Project Environment

  • Create a new directory for your project and open it in VS Code.
  • Create a new file called image_classifier.py.

2. Develop the Classifier

Add the following code to image_classifier.py, which outlines the entire process from data loading to model training:

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

# Load and prepare the CIFAR-10 dataset
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0  # Normalize pixel values

# Define the model architecture
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10)
])

# Compile and train the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))

# Evaluate and save the model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest accuracy: {test_acc}')
model.save('cifar10_model.h5')

# Plot training history for accuracy
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()

3. Set Up Prediction Capabilities

Create a new file called predict.py for making predictions:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

model = tf.keras.models.load_model('cifar10_model.h5')
(_, _), (test_images, test_labels) = tf.keras.datasets.cifar10.load_data()
test_images = test_images / 255.0
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

def plot_image(i, predictions_array, true_label, img):
    true_label, img = true_label[i][0], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap=plt.cm.binary)
    predicted_label = np.argmax(predictions_array)
    color = 'blue' if predicted_label == true_label else 'red'
    plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                         100*np.max(predictions_array),
                                         class_names[true_label]),
                                         color=color)

predictions = model.predict(test_images)
num_images = 15
plt.figure(figsize=(10, 10))
for i in range(num_images):
    plt.subplot(5, 3, i+1)
    plot_image(i, predictions[i], test_labels, test_images)
plt.tight_layout()
plt.show()

4. Manage Dependencies

Create a requirements.txt file with these contents:

tensorflow
matplotlib
numpy

Open the integrated terminal in VS Code (View → Terminal) and run:

pip install -r requirements.txt

5. Execute the Scripts

  • Train the model: Run python image_classifier.py in the terminal.
  • View predictions: After training, run python predict.py.

Enhancements and Best Practices:

  • Error Handling: Implement try-except blocks around data loading and model training steps to handle potential issues gracefully.
  • Git Integration: Use Git for version control. Initialize a Git repository in your project directory and commit changes regularly.
  • Performance Tips: Consider using a TensorFlow GPU installation if you have access to GPU resources to speed up model training.
  • Interactive Plots: Replace matplotlib with Plotly for interactive plots, enhancing the visualization experience.

Why This Demo?

This demo leverages VS Code’s robust features for a complete machine learning workflow, from writing and running Python code to visualizing data. It demonstrates essential practices like data preprocessing, model building, and evaluation, making it a solid foundation for further exploration in machine learning.

This demo showcases several VS Code features:

  1. File management and creation
  2. Code editing with syntax highlighting
  3. Integrated terminal usage
  4. Python environment management
  5. Running Python scripts
  6. Viewing output and plots

It also demonstrates a practical machine learning workflow:

  1. Loading and preprocessing data
  2. Defining and training a neural network
  3. Evaluating model performance
  4. Saving and loading a trained model
  5. Making predictions on new data
  6. Visualizing results

This demo is non-trivial as it involves creating a convolutional neural network for image classification, but it’s not too difficult as it uses a well-known dataset and a straightforward model architecture. It’s a good starting point for exploring more complex machine learning projects in VS Code.