Machine Learning

Nulexpr: The “Faster than Lickpy” Library reports most scientists who have never used

One day, I found a library I never heard before. Was called Rier.

I quickly added because of certain requests made of library. In particular, it meant that some complicated numbers of numbers, it would reach 15 times as soon as possible.

I was impressed because, so far, the incense has been prevented from its rulership at the Psython price. Especially with Data Science, NUMPY is a typewriter, analyzing data and exemplary training. Anything we can use to remove everything else of our programs will be accepted. Therefore, I decided to put on the claims for self-examination.

You can find the link in the number room at the end of this article.

What is halfxpr?

According to the GitUB, Inu000XPR page is a quick analytical to analyze NUNPY numbers. Using it, the lectures that work in the rails are burnt and use less memory rather than making the same calculation in Python and other libraries, such as profits.

In addition, as the numbered, NUMEXPR can use all your Cores Cores, they appear often resulting in the highest gross combustion in comparison with the numpy.

Setting up the environmental environment

Before we start installing codes, let us support our development environment. Doing the best to create a different Python environment when you can install any needed software and test codes, know whatever you do in this area. I am using collar to this, but you can use any way you know better.

If you want to decrease the miningology and you don't have it you are, you must add a minicanda first. Find this link:

1 / Create our new Developer Nature and add required libraries

(base) $ conda create -n numexpr_test python=3.12-y
(base) $ conda activate numexpr
(numexpr_test) $ pip install numexpr
(numexpr_test) $ pip install jupyter

2 / Stop JOYTER
Now type jupyter notebook in your order. You should see the Jusster brochure open in your browser. If that doesn't automatically, you may be able to see the information screefil after jupyter notebook command. Next to the floor, you will receive the URL to copy and paste on your browser to present Jusster Nezebook.

Your URL will be different with mine, but you should look like such a thing: –

Comparison of Nulexpr and Numpy

To compare functionality, we will use a series of number value using the Innes and number, and time for both programs.

Example 1 – Simple Additional Calculation
In this example, we use integrated two of the 5000 major times.

import numpy as np
import numexpr as ne
import timeit

a = np.random.rand(1000000)
b = np.random.rand(1000000)

# Using timeit with lambda functions
time_np_expr = timeit.timeit(lambda: 2*a + 3*b, number=5000)
time_ne_expr = timeit.timeit(lambda: ne.evaluate("2*a + 3*b"), number=5000)

print(f"Execution time (NumPy): {time_np_expr} seconds")
print(f"Execution time (NumExpr): {time_ne_expr} seconds")

>>>>>>>>>>>


Execution time (NumPy): 12.03680682599952 seconds
Execution time (NumExpr): 1.8075962659931974 seconds

I have to say, that is a wonderful start from the number letter of the number. I am doing that upgraded 6 times over Nuunpy Runtime.

Let's see twice that both jobs return with the same results.


# Arrays to store the results
result_np = 2*a + 3*b
result_ne = ne.evaluate("2*a + 3*b")

# Ensure the two new arrays are equal
arrays_equal = np.array_equal(result_np, result_ne)
print(f"Arrays equal: {arrays_equal}")

>>>>>>>>>>>>

Arrays equal: True

Example 2 – Count the PI using Monte Carlo Simulation

Our second example will examine the case of a more complex use of the actual land applications.

Monte Carlo Circumstances Include multilingual Derations of the random process to measure program structures, which can work the most.

In this case, we will use Monto Carlo to calculate the PI value. This is a recognized example where we take the square in the length of a single unit and write a circle of a quarter within it with a single unit radius. Quarter / 4) / 1, and we are able to increase this four talk to find out π itself.

Therefore, when we look at the Medrammes (x, y) points to all the lies in or on the square borders, as the number of points are more common in the number of points to PI.

First, the performance of the nucyy.

import numpy as np
import timeit

def monte_carlo_pi_numpy(num_samples):
    x = np.random.rand(num_samples)
    y = np.random.rand(num_samples)
    inside_circle = (x**2 + y**2) <= 1.0
    pi_estimate = (np.sum(inside_circle) / num_samples) * 4
    return pi_estimate

# Benchmark the NumPy version
num_samples = 1000000
time_np_expr = timeit.timeit(lambda: monte_carlo_pi_numpy(num_samples), number=1000)
pi_estimate = monte_carlo_pi_numpy(num_samples)

print(f"Estimated Pi (NumPy): {pi_estimate}")
print(f"Execution Time (NumPy): {time_np_expr} seconds")

>>>>>>>>

Estimated Pi (NumPy): 3.144832
Execution Time (NumPy): 10.642843848007033 seconds

Now, using the NUMEXPR.

import numpy as np
import numexpr as ne
import timeit

def monte_carlo_pi_numexpr(num_samples):
    x = np.random.rand(num_samples)
    y = np.random.rand(num_samples)
    inside_circle = ne.evaluate("(x**2 + y**2) <= 1.0")
    pi_estimate = (np.sum(inside_circle) / num_samples) * 4  # Use NumPy for summation
    return pi_estimate

# Benchmark the NumExpr version
num_samples = 1000000
time_ne_expr = timeit.timeit(lambda: monte_carlo_pi_numexpr(num_samples), number=1000)
pi_estimate = monte_carlo_pi_numexpr(num_samples)

print(f"Estimated Pi (NumExpr): {pi_estimate}")
print(f"Execution Time (NumExpr): {time_ne_expr} seconds")

>>>>>>>>>>>>>>>

Estimated Pi (NumExpr): 3.141684
Execution Time (NumExpr): 8.077501275009126 seconds

OK, so the speed would impress the same time, but 20% of improvement were not bad. The reason for the reason that the NUMEXPR does not have a SUM () a fixed function, so we had to go back to Numpy for that job.

Example 3 – Implement Solobe filter filter

In this example, we will use the Solese filter filter. The SOBEL filter is usually used in the text of the image found in the edge. The color is a graphical stiffness in the gradient of each pixel, highlighting the edges and the alteration changes. Our photo of installation is Taj Mahal in India.

The first photo is Yury Taranik (license from Shutterstock)

Let's look at the nunpy code running first and time it.

import numpy as np
from scipy.ndimage import convolve
from PIL import Image
import timeit

# Sobel kernels
sobel_x = np.array([[-1, 0, 1],
                    [-2, 0, 2],
                    [-1, 0, 1]])

sobel_y = np.array([[-1, -2, -1],
                    [ 0,  0,  0],
                    [ 1,  2,  1]])

def sobel_filter_numpy(image):
    """Apply Sobel filter using NumPy."""
    img_array = np.array(image.convert('L'))  # Convert to grayscale
    gradient_x = convolve(img_array, sobel_x)
    gradient_y = convolve(img_array, sobel_y)
    gradient_magnitude = np.sqrt(gradient_x**2 + gradient_y**2)
    gradient_magnitude *= 255.0 / gradient_magnitude.max()  # Normalize to 0-255
    
    return Image.fromarray(gradient_magnitude.astype(np.uint8))

# Load an example image
image = Image.open("/mnt/d/test/taj_mahal.png")

# Benchmark the NumPy version
time_np_sobel = timeit.timeit(lambda: sobel_filter_numpy(image), number=100)
sobel_image_np = sobel_filter_numpy(image)
sobel_image_np.save("/mnt/d/test/sobel_taj_mahal_numpy.png")

print(f"Execution Time (NumPy): {time_np_sobel} seconds")

>>>>>>>>>

Execution Time (NumPy): 8.093792188999942 seconds

And now the number code.

import numpy as np
import numexpr as ne
from scipy.ndimage import convolve
from PIL import Image
import timeit

# Sobel kernels
sobel_x = np.array([[-1, 0, 1],
                    [-2, 0, 2],
                    [-1, 0, 1]])

sobel_y = np.array([[-1, -2, -1],
                    [ 0,  0,  0],
                    [ 1,  2,  1]])

def sobel_filter_numexpr(image):
    """Apply Sobel filter using NumExpr for gradient magnitude computation."""
    img_array = np.array(image.convert('L'))  # Convert to grayscale
    gradient_x = convolve(img_array, sobel_x)
    gradient_y = convolve(img_array, sobel_y)
    gradient_magnitude = ne.evaluate("sqrt(gradient_x**2 + gradient_y**2)")
    gradient_magnitude *= 255.0 / gradient_magnitude.max()  # Normalize to 0-255
    
    return Image.fromarray(gradient_magnitude.astype(np.uint8))

# Load an example image
image = Image.open("/mnt/d/test/taj_mahal.png")

# Benchmark the NumExpr version
time_ne_sobel = timeit.timeit(lambda: sobel_filter_numexpr(image), number=100)
sobel_image_ne = sobel_filter_numexpr(image)
sobel_image_ne.save("/mnt/d/test/sobel_taj_mahal_numexpr.png")

print(f"Execution Time (NumExpr): {time_ne_sobel} seconds")

>>>>>>>>>>>>>

Execution Time (NumExpr): 4.938702256011311 seconds

In this event, the use of the NumeExpr, resulting in a positive outcome, by working closest to twice as much.

Here's what a picture found on the edge looks like.

Photo by the writer

Example 4 – Fourier Series Axistation

It is well-known that the complex tasks of the times can be adjusted through a series of waves with well organized to each other. Excessive, even the square wave can be easily leases in this way. The method is called Fourier Series Aximation. Although close, we can approach the development of a title wave as a memory and computational dose and allow.

Statistics after all this is not the main focus. Of course knowing that when we increase the amount of Iterations, the running time arises.

import numpy as np
import numexpr as ne
import time
import matplotlib.pyplot as plt

# Define the constant pi explicitly
pi = np.pi

# Generate a time vector and a square wave signal
t = np.linspace(0, 1, 1000000) # Reduced size for better visualization
signal = np.sign(np.sin(2 * np.pi * 5 * t))

# Number of terms in the Fourier series
n_terms = 10000

# Fourier series approximation using NumPy
start_time = time.time()
approx_np = np.zeros_like
for n in range(1, n_terms + 1, 2):
    approx_np += (4 / (np.pi * n)) * np.sin(2 * np.pi * n * 5 * t)
numpy_time = time.time() - start_time

# Fourier series approximation using NumExpr
start_time = time.time()
approx_ne = np.zeros_like
for n in range(1, n_terms + 1, 2):
    approx_ne = ne.evaluate("approx_ne + (4 / (pi * n)) * sin(2 * pi * n * 5 * t)", local_dict={"pi": pi, "n": n, "approx_ne": approx_ne, "t": t})
numexpr_time = time.time() - start_time

print(f"NumPy Fourier series time: {numpy_time:.6f} seconds")
print(f"NumExpr Fourier series time: {numexpr_time:.6f} seconds")

# Plotting the results
plt.figure(figsize=(10, 6))

plt.plot(t, signal, label='Original Signal (Square Wave)', color='black', linestyle='--')
plt.plot(t, approx_np, label='Fourier Approximation (NumPy)', color='blue')
plt.plot(t, approx_ne, label='Fourier Approximation (NumExpr)', color='red', linestyle='dotted')

plt.title('Fourier Series Approximation of a Square Wave')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.grid(True)
plt.show()

And the result?

Photo by the writer

That is another good results. Nulexpris shows 5 improvements in NUMPY in this event.

Summary

NUMPEPP and NUMEXPR Both libraries used for the Python varied prices. Each has different power and uses different cases, making them ready for different types of jobs. Here, we compare their performance and appropriate integration services, focus on the examples such as easy add to complex requests, such as the use of the Sobel Filter.

When I saw that the speed of 15x sworn in my exam, no doubt NumberPp could be quickly beneficial than many situations.

If you are the heavy user of the nunpy and you need to remove everything else from your code, I recommend trying a library. Besides the fact that not all stadium codes can be repeated using inNexprar, no lowest, and browsing can surprise you.

For more information on the Litexpper Library, check the GitubB page here.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button