0% found this document useful (0 votes)
8 views4 pages

Linear, Quadratic, Power Fits & Correlation

Python codes for regression lines and curve fitting

Uploaded by

groomhot gok
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Linear, Quadratic, Power Fits & Correlation

Python codes for regression lines and curve fitting

Uploaded by

groomhot gok
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Y = ax + b

import numpy as np
import [Link] as plt
from [Link] import curve_fit
def linear_func(x, a, b):
return a * x + b
def get_numeric_input(prompt):
while True:
try:
return [Link]([float([Link]()) for val in input(prompt).split(',')])
except ValueError:
print("Invalid input. Please enter comma-separated numeric values.")
x = get_numeric_input("Enter values for x (comma-separated): ")
y = get_numeric_input("Enter values for y (comma-separated): ")
import warnings
[Link]("ignore")
try:
params, _ = curve_fit(linear_func, x, y)
a, b = params
equation_str = f'Final equation: y = {a:.3f}x {"+" if b >= 0 else "-"} {abs(b):.3f}'
print(f'Optimized parameters: a={a:.3f}, b={b:.3f}')
print(equation_str)
[Link](x, y, label='Data')
[Link](x, linear_func(x, a, b), label=f'Fit: y={a:.3f}x{"+" if b >= 0 else "-
"}{abs(b):.3f}', color='red')
[Link]()
[Link]('x')
[Link]('y')
[Link]('Linear Fit')
[Link](True)
plt.tight_layout()
[Link]()
except RuntimeError:
print("Error: Curve fit failed. Please check your data.")
y = ax2+bx + c
import numpy as np
import [Link] as plt
from [Link] import curve_fit
def quadratic_func(x, a, b, c):
return a + b * x + c * x**2
def get_numeric_input(prompt):
while True:
try:
return [Link]([float([Link]()) for val in input(prompt).split(',')])
except ValueError:
print("Invalid input. Please enter comma-separated numeric values.")
x = get_numeric_input("Enter values for x (comma-separated): ")
y = get_numeric_input("Enter values for y (comma-separated): ")
import warnings
[Link]("ignore")
try:
params, _ = curve_fit(quadratic_func, x, y)
a, b, c = params
b_str, c_str = (f'{val:.3f}' if val >= 0 else f'-{-val:.3f}' for val in [b, c])
equation_str = f'y = {a:.3f} + {b_str}x + {c_str}x^2'
print(f'Optimized parameters: a={a:.3f}, b={b:.3f}, c={c:.3f}')
print(f'Final equation: {equation_str}')
[Link](x, y, label='Data')
[Link](x, quadratic_func(x, a, b, c), label=f'Fit: {equation_str}', color='red')
[Link]()
[Link]('x')
[Link]('y')
[Link]('Quadratic Fit')
[Link](True)
plt.tight_layout()
[Link]()
except RuntimeError:
print("Error: Curve fit failed. Please check your data.")
y = axb
import numpy as np
import [Link] as plt
from [Link] import curve_fit
def power_law_func(x, a, b):
return a * x**b
def get_numeric_input(prompt):
while True:
try:
return [Link]([float([Link]()) for val in input(prompt).split(',')])
except ValueError:
print("Invalid input. Please enter comma-separated numeric values.")
x = get_numeric_input("Enter values for x (comma-separated): ")
y = get_numeric_input("Enter values for y (comma-separated): ")
import warnings
[Link]("ignore")
try:
params, _ = curve_fit(power_law_func, x, y)
a, b = params
b_str = f'{b:.3f}' if b >= 0 else f'-{-b:.3f}'
equation_str = f'y = {a:.3f}x^{b_str}'
print(f'Optimized parameters: a={a:.3f}, b={b:.3f}')
print(f'Final equation: {equation_str}')
[Link](x, y, label='Data')
[Link](x, power_law_func(x, a, b), label=f'Fit: {equation_str}', color='red')
[Link]()
[Link]('x')
[Link]('y')
[Link]('Power Law Fit')
[Link](True)
plt.tight_layout()
[Link]()
except RuntimeError:
print("Error: Curve fit failed. Please check your data.")

Correlation
import numpy as np
def get_numeric_input(prompt):
while True:
try:
return [Link]([float([Link]()) for val in input(prompt).split(',')])
except ValueError:
print("Invalid input. Please enter comma-separated numeric values.")
x = get_numeric_input("Enter values for x (comma-separated): ")
y = get_numeric_input("Enter values for y (comma-separated): ")
if len(x) != len(y):
print("Error: The number of elements in x and y must be the same.")
else:
correlation = [Link](x, y)[0, 1]
print(f'Correlation coefficient: {correlation:.2f}')
Regression Lines
import numpy as np
import [Link] as plt
from [Link] import linregress
def get_numeric_input(prompt):
while True:
try:
return [Link]([float([Link]()) for val in input(prompt).split(',')])
except ValueError:
print("Invalid input. Please enter comma-separated numeric values.")
x = get_numeric_input("Enter values for x (comma-separated): ")
y = get_numeric_input("Enter values for y (comma-separated): ")
if len(x) != len(y):
print("Error: The number of elements in x and y must be the same.")
else:
def plot_regression(x, y, xlabel, ylabel, color, title):
slope, intercept, r_value, _, _ = linregress(x, y)
[Link](x, y)
[Link](x, slope * x + intercept, color=color,
label=f'{ylabel}={slope:.2f}{xlabel}+{intercept:.2f}')
[Link]()
[Link](xlabel)
[Link](ylabel)
[Link](title)
[Link](True)
print(f'Slope {ylabel} on {xlabel}: {slope:.2f}, Intercept {ylabel} on {xlabel}:
{intercept:.2f}')
print(f'R-squared {ylabel} on {xlabel}: {r_value**2:.2f}')
[Link](figsize=(12, 8))
[Link](2, 1, 1)
plot_regression(x, y, 'x', 'y', 'red', 'Linear Regression y on x')
[Link](2, 1, 2)
plot_regression(y, x, 'y', 'x', 'blue', 'Linear Regression x on y')
plt.tight_layout()
[Link]()

You might also like