проверь мою домашку
если правильно пиши правильно
если неправильно - исправляй
все мои изменения идут после фразы # YOUR CODE HERE. рядом с принтом комментарии - то что мне вывел код

вот начало файла Trees_Szczecin.csv
Latin species	Tree height	Coronal diameter	Date Modification	X coordinate	Y coordinate	Longitude	Latitude
Taxus	3.50	7.00	2022-09-20	5470800.17	5922446.63	14.56	53.43
Acer	22.50	18.00	2022-12-02	5471000.01	5922475.48	14.56	53.43

1) We will reuse the tree data from session 10.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import stats

alltrees = pd.read_csv("Trees_Szczecin.csv", sep=";")
alltrees["Coronal diameter"] = pd.to_numeric(alltrees["Coronal diameter"], errors="coerce")
alltrees.dropna(inplace=True, subset=["Tree height", "Coronal diameter"])
alltrees.reset_index(inplace=True, drop=True)
alltrees.head()

1) a) Drop all columns but "Tree height" and "Coronal diameter" from *alltrees* for efficiency. Take a sample of 500 trees without replacement from *alltrees* and call it *treesample*. 
# YOUR CODE HERE
alltrees = alltrees[["Tree height", "Coronal diameter"]]
treesample = alltrees.sample(n=500, replace=False, random_state=42)

print(treesample.shape[0]) #500

1) b) Use the code from the session to compute the slope and intercept for a linear regression with x = "Tree height" and y = "Coronal diameter" in *treesample*. Call them *sampslope* and *sampint*, respectively

# YOUR CODE HERE
x = treesample["Tree height"].values
y = treesample["Coronal diameter"].values

n = len(x)
sum_x = np.sum(x)
sum_y = np.sum(y)
sum_xy = np.sum(x * y)
sum_x2 = np.sum(x**2)

sampslope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x**2)
sampint = (sum_y - sampslope * sum_x) / n

print(sampslope, sampint) #0.5673610985513837 0.4978286278498044

1) c) Reuse the code from the session to compute a bootstrapped 95% CI for the regression slope based on the sample, with 100 bootstrapped resamplings. Call the result *boot_slope_CI*.

# YOUR CODE HERE
def standard_units(any_numbers:np.ndarray):
    return (any_numbers - np.mean(any_numbers))/np.std(any_numbers) 

def correlation(x:np.ndarray, y:np.ndarray):
    return np.mean(standard_units(x)*standard_units(y))

def slope(x:np.ndarray, y:np.ndarray):
    r = correlation(x, y)
    return r*np.std(y)/np.std(x)

def bootstrap_slope_CI(sample: np.ndarray, n: int):
    slope_list = []
    for _ in range(n):
        idx = np.random.choice(sample.shape[0], sample.shape[0], replace=True)
        bootsamp = sample[idx]
        slopei = slope(bootsamp[:, 0], bootsamp[:, 1])
        slope_list.append(slopei)
    CI = np.quantile(slope_list, [0.025, 0.975])
    return CI

sample_data = treesample[["Tree height", "Coronal diameter"]].values
boot_slope_CI = bootstrap_slope_CI(sample_data, 100)

print(boot_slope_CI) #[0.50675736 0.61095415]

1) d) Modify the code from the session to compute a bootstrapped 95% CI for the regression **intercept** based on the sample, with 100 bootstrapped resamplings. Call the result *boot_int_CI*. Make the function return the intercepts from the bootstrapped resamplings as well as the CI. Call the intercepts *boot_inties*.

# YOUR CODE HERE
def intercept(x:np.ndarray, y:np.ndarray):
    return np.mean(y) - slope(x,y)*np.mean(x)

def bootstrap_int_CI(sample: np.ndarray, n: int):
    int_list = []
    for i in range(n):
        idx = np.random.choice(sample.shape[0], sample.shape[0], replace=True)
        bootsamp = sample[idx]
        x = bootsamp[:, 0]
        y = bootsamp[:, 1]
        int_i = intercept(x, y)
        int_list.append(int_i)
    CI = np.quantile(int_list, [0.025, 0.975])
    return int_list, CI

boot_inties, boot_int_CI = bootstrap_int_CI(sample_data, 100)
print(boot_int_CI) #print(boot_int_CI)

1) e) Plot a histogram of the *boot_inties*, with the CI also marked in some way.
# YOUR CODE HERE
plt.figure(figsize=(10, 6))

plt.hist(boot_inties, bins=20, color='skyblue', edgecolor='black', alpha=0.7, label='Bootstrapped intercepts')

plt.axvline(x=boot_int_CI[0], color='red', linestyle='--', linewidth=2, 
            label=f'Lower CI: {boot_int_CI[0]:.2f}')
plt.axvline(x=boot_int_CI[1], color='green', linestyle='--', linewidth=2, 
            label=f'Upper CI: {boot_int_CI[1]:.2f}')

mean_int = np.mean(boot_inties)
plt.axvline(x=mean_int, color='black', linestyle='-', linewidth=2, 
            label=f'Mean: {mean_int:.2f}')

plt.title('Distribution of Bootstrapped Intercept Values\nwith 95% Confidence Interval', fontsize=14)
plt.xlabel('Intercept Value', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.legend(fontsize=10)
plt.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.show()

2) a) Compute the predictions and residuals for the linear regression in our sample, and call them *predictions* and *residuals*.

# YOUR CODE HERE
x = treesample["Tree height"].values
y = treesample["Coronal diameter"].values

predictions = sampint + sampslope * x
residuals = y - predictions

print(predictions.shape, residuals.shape)

2) b) Plot the residuals as a histogram to visually inspect their distribution.
# YOUR CODE HERE
plt.figure(figsize=(10, 6))
plt.hist(residuals, bins=20, color='skyblue', edgecolor='black')

plt.title('Distribution of Regression Residuals', fontsize=14)
plt.xlabel('Residual Values (Actual - Predicted)', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(axis='y', alpha=0.3)

plt.axvline(x=0, color='red', linestyle='--', linewidth=1)

plt.tight_layout()
plt.show()

2) c) Reuse our code from the lab session to perform an F test on the linear regression of Coronal diameter on Tree height in our sample. Call the F value *F_value* and the p value *p_value*.

# YOUR CODE HERE
SSM = np.sum((predictions - np.mean(y))**2)
dfM = 1

SSE = np.sum(residuals**2)
dfE = len(y) - 2

MSM = SSM / dfM
MSE = SSE / dfE

F_value = MSM / MSE
p_value = 1 - stats.f.cdf(F_value, dfM, dfE)

print("Sample F value: " + str(F_value) + ",\nSample p value: " + str(p_value) + ",\nSample slope: " + str(sampslope))

#Sample F value: 757.547903545644,
#Sample p value: 1.1102230246251565e-16,
#Sample slope: 0.5673610985513837