Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Problem: Add Rouge Score #194

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions Problems/image_basic_contrast_calculator/learn.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculating Contrast of a Grayscale Image</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
line-height: 1.6;
max-width: 800px;
margin: 0 auto;
padding: 20px;
color: #333;
}
h2 {
color: #2c5282;
border-bottom: 2px solid #4299e1;
padding-bottom: 8px;
}
h3 {
color: #2d3748;
margin-top: 24px;
}
p {
margin: 16px 0;
}
ul {
padding-left: 20px;
}
li {
margin: 8px 0;
}
strong {
color: #2c5282;
}
.math-block {
background: #f7fafc;
padding: 16px;
border-radius: 8px;
margin: 20px 0;
text-align: center;
font-size: 1.2em;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</head>
<body>
<h2>Calculating Contrast of a Grayscale Image</h2>

<p>Contrast in a grayscale image refers to the difference in luminance or color that makes an object distinguishable. Here are several methods to calculate contrast:</p>

<h3>1. Basic Contrast Calculation</h3>
<p>The simplest way to define the contrast of a grayscale image is by using the difference between the maximum and minimum pixel values:</p>
<div class="math-block">
\[
\text{Contrast} = \max(I) - \min(I)
\]
</div>

<h3>2. RMS Contrast</h3>
<p>The Root Mean Square (RMS) contrast considers the standard deviation of pixel intensities:</p>
<div class="math-block">
\[
\text{RMS Contrast} = \frac{\sigma}{\mu}
\]
</div>

<h3>3. Michelson Contrast</h3>
<p>Michelson contrast is defined as:</p>
<div class="math-block">
\[
C = \frac{I_{\text{max}} - I_{\text{min}}}{I_{\text{max}} + I_{\text{min}}}
\]
</div>

<h3>4. Histogram Analysis</h3>
<p>Another method involves analyzing the histogram of pixel intensities:</p>
<ul>
<li>Compute the histogram of the grayscale image.</li>
<li>Identify peaks to determine background and foreground values.</li>
<li>Calculate contrasts based on pixel values relative to these levels.</li>
</ul>

<h3>5. Example Calculation</h3>
<p>For instance, consider a grayscale image with pixel values ranging from 50 to 200:</p>
<ul>
<li><strong>Maximum Pixel Value:</strong> 200</li>
<li><strong>Minimum Pixel Value:</strong> 50</li>
<li><strong>Contrast Calculation:</strong></li>
<div class="math-block">
\[
\text{Contrast} = 200 - 50 = 150
\]
</div>
</ul>

<h3>Conclusion</h3>
<p>Selecting an appropriate method for calculating contrast depends on your specific needs and the characteristics of the image being analyzed.</p>

</body>
</html>
51 changes: 51 additions & 0 deletions Problems/image_basic_contrast_calculator/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import numpy as np

def calculate_contrast(img):
"""
Calculate the contrast of a grayscale image.

Args:
img (numpy.ndarray): 2D array representing a grayscale image with pixel values between 0 and 255.

Returns:
float: Contrast value rounded to 3 decimal places.
"""

# Find the maximum and minimum pixel values
max_pixel = np.max(img)
min_pixel = np.min(img)

# Calculate contrast
contrast = max_pixel - min_pixel

return round(float(contrast), 3)

def test_calculate_contrast():
# Test case 1: Simple gradient
img1 = np.array([[0, 50], [200, 255]])
expected_output1 = 255
assert calculate_contrast(img1) == expected_output1, "Test case 1 failed"

# Test case 2: Uniform image (all pixels same)
img2 = np.array([[128, 128], [128, 128]])
expected_output2 = 0
assert calculate_contrast(img2) == expected_output2, "Test case 2 failed"

# Test case 3: All black
img3 = np.zeros((10, 10), dtype=np.uint8)
expected_output3 = 0
assert calculate_contrast(img3) == expected_output3, "Test case 3 failed"

# Test case 4: All white
img4 = np.ones((10, 10), dtype=np.uint8) * 255
expected_output4 = 0
assert calculate_contrast(img4) == expected_output4, "Test case 4 failed"

# Test case 5: Random values
img5 = np.array([[10, 20, 30], [40, 50, 60]])
expected_output5 = 50
assert calculate_contrast(img5) == expected_output5, "Test case 5 failed"

if __name__ == "__main__":
test_calculate_contrast()
print("All contrast test cases passed.")
55 changes: 55 additions & 0 deletions Problems/rouge_score/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import numpy as np
from collections import Counter
from typing import Dict

def get_ngrams(text: str, n: int) -> Counter:
"""
Convert text into n-grams and return their counts.

Args:
text (str): Input text
n (int): Size of n-grams

Returns:
Counter: Dictionary with n-grams as keys and their counts as values
"""
words = text.lower().split()
ngrams = [tuple(words[i:i+n]) for i in range(len(words)-n+1)]
return Counter(ngrams)

def rouge_n(reference: str, candidate: str, n: int = 1) -> Dict[str, float]:
"""
Calculate ROUGE-N score between reference and candidate texts.

Args:
reference (str): Reference text
candidate (str): Candidate text to evaluate
n (int): Size of n-grams to consider (default: 1)

Returns:
dict: Dictionary containing precision, recall, and f1-score
"""
# Get n-gram counts
ref_ngrams = get_ngrams(reference, n)
cand_ngrams = get_ngrams(candidate, n)

# Convert to numpy arrays for faster computation
all_ngrams = list(set(ref_ngrams) | set(cand_ngrams))
ref_vec = np.array([ref_ngrams[ng] for ng in all_ngrams])
cand_vec = np.array([cand_ngrams[ng] for ng in all_ngrams])

# Calculate overlap using element-wise minimum
overlap = np.minimum(ref_vec, cand_vec).sum()

# Calculate precision and recall
precision = overlap / max(cand_vec.sum(), 1e-10) # Avoid division by zero
recall = overlap / max(ref_vec.sum(), 1e-10)

# Calculate F1 score
f1 = 2 * precision * recall / max(precision + recall, 1e-10)

return {
'precision': float(precision),
'recall': float(recall),
'f1': float(f1)
}
98 changes: 98 additions & 0 deletions Problems/vector_dot_product/learn.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculating the Dot Product of Two Vectors</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
line-height: 1.6;
max-width: 800px;
margin: 0 auto;
padding: 20px;
color: #333;
}
h2 {
color: #2c5282;
border-bottom: 2px solid #4299e1;
padding-bottom: 8px;
}
h3 {
color: #2d3748;
margin-top: 24px;
}
p {
margin: 16px 0;
}
ul {
padding-left: 20px;
}
li {
margin: 8px 0;
}
strong {
color: #2c5282;
}
.math-block {
background: #f7fafc;
padding: 16px;
border-radius: 8px;
margin: 20px 0;
text-align: center;
font-size: 1.2em;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</head>
<body>
<h2>Calculating the Dot Product of Two Vectors</h2>

<p>The dot product, also known as the scalar product, is a mathematical operation that takes two equal-length vectors and returns a single number. It is widely used in physics, geometry, and linear algebra.</p>

<h3>1. Formula for the Dot Product</h3>
<p>The dot product of two vectors \( \mathbf{a} \) and \( \mathbf{b} \), each of length \( n \), is calculated as follows:</p>
<div class="math-block">
\[
\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i
\]
</div>
<p>This means multiplying corresponding elements of the two vectors and summing up the results.</p>

<h3>2. Geometric Interpretation</h3>
<p>In geometric terms, the dot product can also be expressed as:</p>
<div class="math-block">
\[
\mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| |\mathbf{b}| \cos \theta
\]
</div>
<p>Here:</p>
<ul>
<li>\( |\mathbf{a}| \) and \( |\mathbf{b}| \) are the magnitudes of the vectors.</li>
<li>\( \theta \) is the angle between the two vectors.</li>
</ul>

<h3>3. Properties of the Dot Product</h3>
<ul>
<li><strong>Commutative:</strong> \( \mathbf{a} \cdot \mathbf{b} = \mathbf{b} \cdot \mathbf{a} \)</li>
<li><strong>Distributive:</strong> \( \mathbf{a} \cdot (\mathbf{b} + \mathbf{c}) = \mathbf{a} \cdot \mathbf{b} + \mathbf{a} \cdot \mathbf{c} \)</li>
<li><strong>Orthogonal Vectors:</strong> If \( \mathbf{a} \cdot \mathbf{b} = 0 \), then \( \mathbf{a} \) and \( \mathbf{b} \) are perpendicular.</li>
</ul>

<h3>4. Example Calculation</h3>
<p>Given two vectors:</p>
<ul>
<li>\( \mathbf{a} = [1, 2, 3] \)</li>
<li>\( \mathbf{b} = [4, 5, 6] \)</li>
</ul>
<p>The dot product is calculated as:</p>
<div class="math-block">
\[
\mathbf{a} \cdot \mathbf{b} = (1 \cdot 4) + (2 \cdot 5) + (3 \cdot 6) = 4 + 10 + 18 = 32
\]
</div>

<h3>Conclusion</h3>
<p>The dot product is a fundamental operation in vector algebra, useful in determining angles between vectors, projections, and in many applications across physics and engineering.</p>

</body>
</html>
49 changes: 49 additions & 0 deletions Problems/vector_dot_product/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import numpy as np

def calculate_dot_product(vec1, vec2):
"""
Calculate the dot product of two vectors.

Args:
vec1 (numpy.ndarray): 1D array representing the first vector.
vec2 (numpy.ndarray): 1D array representing the second vector.

Returns:
float: Dot product of the two vectors.
"""
return np.dot(vec1, vec2)

def test_calculate_dot_product():
# Test case 1: Positive numbers
vec1 = np.array([1, 2, 3])
vec2 = np.array([4, 5, 6])
expected_output1 = 32
assert calculate_dot_product(vec1, vec2) == expected_output1, "Test case 1 failed"

# Test case 2: Include negative numbers
vec1 = np.array([-1, 2, 3])
vec2 = np.array([4, -5, 6])
expected_output2 = 4
assert calculate_dot_product(vec1, vec2) == expected_output2, "Test case 2 failed"

# Test case 3: Orthogonal vectors
vec1 = np.array([1, 0])
vec2 = np.array([0, 1])
expected_output3 = 0
assert calculate_dot_product(vec1, vec2) == expected_output3, "Test case 3 failed"

# Test case 4: All zeros
vec1 = np.array([0, 0, 0])
vec2 = np.array([0, 0, 0])
expected_output4 = 0
assert calculate_dot_product(vec1, vec2) == expected_output4, "Test case 4 failed"

# Test case 5: Scalars (single-element vectors)
vec1 = np.array([7])
vec2 = np.array([3])
expected_output5 = 21
assert calculate_dot_product(vec1, vec2) == expected_output5, "Test case 5 failed"

if __name__ == "__main__":
test_calculate_dot_product()
print("All dot product test cases passed.")