import numpy as np
import matplotlib.pyplot as plt

def newton_method(f, f_prime, x0, tolerance=0.00001, max_iterations=100):
    x_values = [x0]
    iterations = 0

    while True:
        x1 = x0 - f(x0) / f_prime(x0)
        x_values.append(x1)
        iterations += 1

        if abs(x1 - x0) < tolerance or iterations >= max_iterations:
            print(f"iteration complete! {iterations}")
            break

        x0 = x1

    return x_values

# Define the function and its derivative
def function(x):
    return 0.5 * x**2

def derivative(x):
    return x
    
 
# Set initial values
initial_guess = 50

# Run Newton's method
resulting_values = newton_method(function, derivative, initial_guess)

# Plot the convergence process
x_values = np.linspace(-50, 50, 1000)
y_values = function(x_values)

plt.plot(x_values, y_values, label='object Function f(x) = 0.5 * x^2')
plt.scatter(resulting_values, function(np.array(resulting_values)), color='red', label='Convergence Points')
plt.title("Newton's Method in Convex Function")
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()

 

import random
import matplotlib.pyplot as plt

def convex_function(x):
    return 0.5 * x**2  # 예제로 사용할 convex 함수: f(x) = 0.5 * x^2

def convex_function_diff(x):
    return x

def plot_convergence(maxiterations = 50, threshold = 0.1):
    x_values = np.linspace(-50, 50, 1000)
    y_values = convex_function(x_values)

    plt.plot(x_values, y_values, label='object Function f(x) = 0.5 * x^2')
    plt.title('Convergence of a Convex Function')
    plt.xlabel('x')
    plt.ylabel('f(x)')

    # 초기값 설정
    initial_x = random.randint(-50, 50)
    learning_rate = 0.1
    iterations = 50

    new_x = initial_x
    x_values_history = []
    for i in range(maxiterations):
        x_values_history.append(new_x)
        gradient = convex_function_diff(new_x)  # f'(x) = x for this example
        next_x = new_x - learning_rate * gradient

        if (abs(new_x - next_x) < threshold):
            print(f"iteration complete! {i}")
            break
        new_x = next_x
        

    plt.scatter(x_values_history, convex_function(np.array(x_values_history)), c='red', label='Convergence Points')
    plt.legend()
    plt.show()

# 수렴 과정 plotting
plot_convergence(50,0.00001)

#include <opencv2/opencv.hpp>

int main() {
    // 픽셀 좌표 (예: 객체를 탐지한 픽셀 좌표)
    cv::Point2f pixelPoint(100, 150);

    // 카메라 매트릭스 및 왜곡 계수 (카메라 캘리브레이션에서 얻은 값 사용)
    cv::Mat cameraMatrix = (cv::Mat_<double>(3, 3) << fx, 0, cx, 0, fy, cy, 0, 0, 1);
    cv::Mat distortionCoeffs = (cv::Mat_<double>(1, 5) << k1, k2, p1, p2, k3);

    // 카메라 좌표를 월드 좌표로 변환하는 함수
    cv::Matx44d transformationMatrix; // 여기에 변환 행렬이 저장됨
    cv::solvePnP(objectPoints, imagePoints, cameraMatrix, distortionCoeffs, transformationMatrix);

    // 픽셀 좌표를 카메라 좌표로 변환
    cv::Matx31d pixelCoordinates(pixelPoint.x, pixelPoint.y, 1.0);
    cv::Matx31d cameraCoordinates = cameraMatrix.inv() * pixelCoordinates;

    // 카메라 좌표를 월드 좌표로 변환
    cv::Matx41d worldCoordinatesHomogeneous = transformationMatrix * cv::Matx41d(cameraCoordinates(0), cameraCoordinates(1), cameraCoordinates(2), 1.0);
    cv::Matx31d worldCoordinates(worldCoordinatesHomogeneous(0), worldCoordinatesHomogeneous(1), worldCoordinatesHomogeneous(2));

    // 결과 출력
    std::cout << "픽셀 좌표: " << pixelPoint << std::endl;
    std::cout << "월드 좌표: " << worldCoordinates << std::endl;

    return 0;
}

 

-chatgpt

import math
import numpy as np

def get_pivot_position(tableau):
    z = tableau[-1]
    column = next(i for i, x in enumerate(z[:-1]) if x > 0)

    restrictions = []
    for eq in tableau[:-1]:
        el = eq[column]
        restrictions.append(math.inf if el <= 0 else eq[-1] / el)

    row = restrictions.index(min(restrictions))
    return row, column

def pivot_step(tableau, pivot_position):
    new_tableau = [[] for eq in tableau]

    i, j = pivot_position
    pivot_value = tableau[i][j]
    new_tableau[i] = np.array(tableau[i]) / pivot_value

    for eq_i, eq in enumerate(tableau):
        if eq_i != i:
            multiplier = np.array(new_tableau[i]) * tableau[eq_i][j]
            new_tableau[eq_i] = np.array(tableau[eq_i]) - multiplier

    return new_tableau
    
def to_tableau(c, A, b):
    xb = [eq + [x] for eq, x in zip(A, b)]
    z = c + [0]
    return xb + [z]
    
def simplex(c, A, b):
    tableau = to_tableau(c, A, b)

    while can_be_improved(tableau):
        pivot_position = get_pivot_position(tableau)
        tableau = pivot_step(tableau, pivot_position)

    return get_solution(tableau)

def can_be_improved(tableau):
    z = tableau[-1]
    return any(x > 0 for x in z[:-1])

def is_basic(column):
    return sum(column) == 1 and len([c for c in column if c == 0]) == len(column) - 1

def get_solution(tableau):
    columns = np.array(tableau).T
    solutions = []
    for column in columns[:-1]:
        solution = 0
        if is_basic(column):
            one_index = column.tolist().index(1)
            solution = columns[-1][one_index]
        solutions.append(solution)

    return solutions
    

c = [1, 1, 0, 0, 0]
A = [
    [-1, 1, 1, 0, 0],
    [ 1, 0, 0, 1, 0],
    [ 0, 1, 0, 0, 1]
]
b = [2, 4, 4]

solution = simplex(c, A, b)
print('solution: ', solution)

 

출처 : https://radzion.com/blog/operations/simplex

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

// 히스토그램을 계산하고 정규화하는 함수
Mat calcHistNormalized(const Mat &src) {
    Mat hsv;
    cvtColor(src, hsv, COLOR_BGR2HSV);

    // H 채널에 대한 히스토그램 계산
    int h_bins = 256; // 히스토그램 빈의 수
    int histSize[] = { h_bins };
    float h_ranges[] = { 0, 256 };
    const float* ranges[] = { h_ranges };
    int channels[] = { 0 };
    Mat hist;
    calcHist(&hsv, 1, channels, Mat(), hist, 1, histSize, ranges, true, false);

    // 히스토그램 정규화
    normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat());

    return hist;
}

// 코사인 유사도를 계산하는 함수
double cosineSimilarity(const Mat &hist1, const Mat &hist2) {
    return hist1.dot(hist2) / (norm(hist1) * norm(hist2));
}

int main() {
    // 이미지 파일을 로드
    Mat image1 = imread("image1.jpg");
    Mat image2 = imread("image2.jpg");

    if (image1.empty() || image2.empty()) {
        cout << "Could not open or find the image(s)." << endl;
        return -1;
    }

    // 히스토그램 계산 및 정규화
    Mat hist1 = calcHistNormalized(image1);
    Mat hist2 = calcHistNormalized(image2);

    // 코사인 유사도 계산
    double similarity = cosineSimilarity(hist1, hist2);

    cout << "Cosine Similarity: " << similarity << endl;

    return 0;
}

시스템 요구 사항

1. 강화학습 알고리즘이 있어야하고, 커스터 마이징 가능해야 한다.

   -> 강화학습 적용의 확장성

2. Unity 와 같은 시뮬레이션과 연동 가능해야한다.

   -> 환경 적용의 확장성, 가시화 상승

3. 커뮤니티가 활성화 되어 있어야한다.

   -> 많은 정보량

4. 병렬 환경에서도 구동 가능해야한다.

   -> 학습 가속

5. ROS2 와 연동했을때 문제 없어야한다.

   -> 실제 로봇 적용을 고려

 

강화학습 프레임워크 후보

 

1. Ray RLlib


장점:

다양한 알고리즘 지원: RLlib은 다양한 강화 학습 알고리즘을 지원합니다. 이는 연구자가 다양한 알고리즘을 쉽게 실험해 볼 수 있게 합니다.
분산 학습 지원: RLlib은 분산 학습을 지원하며, 이를 통해 대규모의 학습 작업을 처리할 수 있습니다.
다양한 환경 지원: RLlib은 OpenAI Gym 인터페이스를 따르는 다양한 환경을 지원합니다.

 

단점:

복잡성: RLlib은 매우 강력한 도구이지만, 그만큼 복잡성도 높습니다. 이로 인해 학습 곡선이 가파를 수 있습니다.
문서화: RLlib의 문서화는 개선이 필요한 부분이 있습니다. 특히, 고급 기능에 대한 문서화가 부족할 수 있습니다.

https://docs.ray.io/en/master/rllib/

 

RLlib: Industry-Grade Reinforcement Learning — Ray 3.0.0.dev0

Get started with environments supported by RLlib, such as Farama foundation’s Gymnasium, Petting Zoo, and many custom formats for vectorized and multi-agent environments.

docs.ray.io

 

2. Acme

 

https://www.deepmind.com/publications/acme-a-new-framework-for-distributed-reinforcement-learning

 

Acme: A new framework for distributed reinforcement learning

Reinforcement Learning (RL) provides an elegant formalization for the problem of intelligence. In combination with advances in deep learning and increases in computation, this formalization has resulted in powerful solutions to longstanding artificial inte

www.deepmind.com

 

장점:

모듈성: Acme는 간단하고 모듈식 구성 요소를 사용하여 다양한 규모의 실행에서 사용할 수 있는 에이전트를 구축하도록 설계되었습니다. 이는 연구자가 새로운 아이디어를 빠르게 프로토타입화하고 게시된 RL 알고리즘을 재현하는 데 도움이 됩니다.
재현성: Acme는 중요하거나 최신의 알고리즘에 대한 간단한 참조 구현을 제공합니다. 이는 Acme의 설계 결정의 유효성을 입증하는 데 도움이 되며, RL 연구의 재현성에 중요한 기여를 합니다.

 

단점:

알고리즘 지원: Acme는 RLlib에 비해 지원하는 알고리즘의 수가 적습니다. 이는 특정 알고리즘을 사용하려는 연구자에게는 제한적일 수 있습니다.
분산 학습 지원: Acme는 RLlib에 비해 분산 학습 지원이 덜 발달되어 있습니다. 이는 대규모 학습 작업을 처리하는 데 제한적일 수 있습니다.

+ Recent posts