News

日本語 · English · 中文

[Contribution] What to Learn During Internships: Part 1/3 – Basic Tools and Mathematical Optimization

This article explains the foundational tools and mathematical optimization required in Blueqat's engineering roles. It covers numerical computation, data manipulation, visualization, and automatic differentiation using NumPy, Pandas, Matplotlib, and PyTorch, and provides intuitive understanding by formulating representative methods such as gradient-based optimization, combinatorial optimization, and Bayesian optimization in Python.

Given the high demand, I will write down content that engineers should keep in mind for practical engineering tasks. As of early 2026, the content has been significantly updated from a few years ago.

We do not focus much on optimization; machine learning is the main focus. While quantum machine learning is important, the foundation remains classical machine learning. Especially recently, Transformer models are often used. It is common to understand basic MLPs to a certain extent and, even if the model changes, to understand the mathematical model and modify it accordingly.

In terms of fields, time series and image recognition are currently prevalent, while we learn and operate various other models and applications tailored to customers. The basic tool is PyTorch, which serves as the base for executing all quantum computing and machine learning tasks.

Here is the second part
【Contribution】blueqat Intern Course: Practical Models from Regression to Image Classification

Part 1: Environment Setup and Basic Tools

In blueqat's engineering work, we leverage our background in physics and mathematics to perform numerical optimization, data analysis, and machine learning on Python.

Libraries used:

  • NumPy: Numerical computation
  • Pandas: DataFrame processing
  • Matplotlib: Visualization
  • PyTorch: GPU-accelerated numerical computation

First, let's verify the environment.

Verifying and Importing Libraries

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch

NumPy Basics: Vector and Matrix Operations

In mathematical optimization and machine learning, operations involving scalars, vectors, and matrices are central.

For example, the dot product of vectors $\mathbf{x}$ and $\mathbf{y}$ is expressed as follows:

\[\mathbf{x} \cdot \mathbf{y} = \sum_i x_i y_i\]

This can be computed using np.dot(x, y) in NumPy.

# Example of vector operations
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

dot = np.dot(x, y)
print("Dot Product:", dot)

Visualizing Numerical Computation with NumPy

Let's calculate and graph the quadratic function $f(x) = x^2 - 2x + 1$.

x = np.linspace(-3, 5, 100)
f = x**2 - 2*x + 1

plt.plot(x, f)
plt.title("f(x) = x^2 - 2x + 1")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.grid(True)
plt.show()

Dataframe Manipulation with Pandas

Pandas is a library suited for "manipulating tabular data."

For example, consider the following data:

ProductPriceStock
A12010
B2005
C1508
# Create a DataFrame
df = pd.DataFrame({
    "Product": ["A", "B", "C"],
    "Price": [120, 200, 150],
    "Stock": [10, 5, 8]
})

# Basic operations
print(df)
print("\nAverage Price:", df["Price"].mean())
print("Total Stock:", df["Stock"].sum())

# Add a new column
df["Total Value"] = df["Price"] * df["Stock"]
display(df)

Product Price Stock
0 A 120 10
1 B 200 5
2 C 150 8

Average Price: 156.66666666666666
Total Stock: 23
Product Price Stock Total Value
0 A 120 10 1200
1 B 200 5 1000
2 C 150 8 1200

Visualization with Matplotlib

Next, let's visualize the stock quantities using a bar chart.

plt.bar(df["Product"], df["Stock"], color='skyblue')
plt.title("Stock Quantity")
plt.xlabel("Product")
plt.ylabel("Stock")
plt.show()

Automatic Differentiation for Numerical Computation with PyTorch

In physics, optimization, and machine learning, "gradients (derivatives)" are crucial.

PyTorch supports automatic differentiation.

Consider the following function:

\[f(x) = x^2 + 3x + 2\]

Its gradient is:

\[\frac{df}{dx} = 2x + 3\]

Let's compute this automatically using PyTorch.

x = torch.tensor(2.0, requires_grad=True)  # Enable gradient tracking
f = x**2 + 3*x + 2
f.backward()  # Compute gradients
print("f(x) =", f.item())
print("df/dx =", x.grad.item())  # Theoretical value is 2x + 3 = 7

f(x) = 12.0
df/dx = 7.0

Summary of Part 1

LibraryMain Use Case
NumPyNumerical computation (vectors/matrices)
PandasData management/aggregation
MatplotlibVisualization
PyTorchAutomatic differentiation/GPU computation

Part 2: Mathematical Optimization (Optimization Basics)

In previous internships, optimization was covered in considerable detail. However, in machine learning, while optimization is frequently used for mathematical models, it is no longer the primary protagonist. In this section, we cover three representative methods of optimization. Although these are not necessarily applied directly to machine learning models, they frequently arise in business tasks, so it is necessary to remember them.

  1. Gradient-based Optimization
  2. Combinatorial Optimization
  3. Bayesian Optimization

The objective is to
"formulate minimization/maximization problems in Python and gain an intuitive understanding of solution methods."

1. Gradient Descent

This is the most fundamental optimization algorithm, utilized in learning.
To find the minimum value of a function $f(x)$, we move gradually in the direction of the gradient (slope).

\[x_{t+1} = x_t - \eta \frac{df}{dx}\]

Where

  • $\eta$: Learning rate (step size)
  • $\frac{df}{dx}$: Gradient

As an example, we minimize the following function.

\[f(x) = (x - 3)^2 + 1\]
import numpy as np
import matplotlib.pyplot as plt

# Function and its gradient
def f(x):
    return (x - 3)**2 + 1

def df(x):
    return 2 * (x - 3)

# Initialization
x = 10.0
eta = 0.1
history = [x]

# Gradient Descent
for t in range(30):
    x -= eta * df(x)
    history.append(x)

# Plot
x_plot = np.linspace(0, 10, 100)
plt.plot(x_plot, f(x_plot), label="f(x)")
plt.scatter(history, [f(xi) for xi in history], color='red')
plt.title("Gradient Descent Path")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.legend()
plt.grid(True)
plt.show()

print("Approximate minimum x:", x)

2. Combinatorial Optimization

Next is the problem of "selecting the optimal combination from a set of choices." In quantum computing, QUBO is often used; honestly, anything goes, but if working in the quantum industry, knowing QUBO seems essential.

Example: Knapsack Problem

\[\max \sum_i v_i x_i \quad \text{s.t.} \quad \sum_i w_i x_i \le W, \; x_i \in \{0,1\}\]
  • $v_i$: Value
  • $w_i$: Weight
  • $W$: Capacity limit
  • $x_i$: Selected (1) / Not selected (0)
!pip install pulp -q

from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpBinary

# Problem definition
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50

# Create problem
prob = LpProblem("Knapsack", LpMaximize)

# Binary decision variables
x = [LpVariable(f"x{i}", cat=LpBinary) for i in range(3)]

# Objective
prob += lpSum(values[i] * x[i] for i in range(3))

# Constraint
prob += lpSum(weights[i] * x[i] for i in range(3)) <= capacity

# Solve
prob.solve()

print("Selected items:")
for i in range(3):
    print(f"Item {i+1}: {x[i].value()}")

Selected items:
Item 1: 0.0
Item 2: 1.0
Item 3: 1.0

Looking at the results, the combination that maximizes value while satisfying constraints is selected.

Such Integer Optimization is applied to many business tasks such as scheduling, delivery planning, and inventory allocation. To reiterate, in the case of quantum computing, remember QUBO.

3. Bayesian Optimization

Finally, we handle the optimization of black-box functions.
This is useful when gradients cannot be calculated or evaluation is costly.
It can optimize not only continuous variables but also discrete variables and categories.

Algorithm concept:

  1. Evaluate the function at sample points
  2. Approximate the function shape using Gaussian processes
  3. Stochastically select "where to try next" (Acquisition Function)

Through this iteration, we search for the minimum (or maximum) value.

!pip install optuna -q

import optuna
import math

# Objective function (unknown black-box)
def objective(trial):
    x = trial.suggest_float("x", -5, 5)
    return (x - 2)**2 + math.sin(5 * x)

# Run optimization
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=30)

print("Best parameters:", study.best_params)
print("Best value:", study.best_value)

# Plot results
optuna.visualization.matplotlib.plot_optimization_history(study)
plt.show()

Best parameters: {'x': 2.1871381650806523}
Best value: -0.9631868284028522

Intuition behind Bayesian Optimization

  • Exploration: Trying unknown areas
  • Exploitation: Investigating promising areas in detail

By balancing these, we efficiently find the best solution.


Summary of Part 2

MethodUse CaseCharacteristics
Gradient DescentMinimization of continuous functionsSimple, Fast (requires derivatives)
Combinatorial OptimizationDiscrete selection problemsStrong against real-world constraints
Bayesian OptimizationSearch for high-cost functionsHigh sample efficiency

This article was translated from the Japanese original. 日本語で読む

← Latest articles