Hi guys, I’m learning Julia. I would like to ask you a question. How do I insert y3 into the graph?
and then why order 8 comes out with so much overfitting. A more compliant line should emerge as the result of the photo I attach.
In the comments I will attach my result instead.
Can you correct the code where the error is present, because I can’t understand.
Thank you
this is the code i used:
using Plots
using CSV, DataFrames
using LinearAlgebra
# Lettura dei dati come mostrato in precedenza
train_data = Matrix(CSV.read("hw_data.csv", DataFrame, header = false))
x_height = train_data[:,1]
y_weight = train_data[:,2]
# Funzione lineare per il modello
linear_fun(height, a) = a[2] * height + a[1]
# Funzione generatrice di caratteristiche
function Φ(x::Real, k::Integer; μ=165, σ=50)::Vector{Real}
z = (x-μ) / σ
return [z.^i for i=0:k]
end
function approximate_and_error(k)
Φ_matrix = hcat([Φ(x, k) for x in x_height]...)
Φ_matrix = transpose(Φ_matrix) # Trasponiamo per avere le dimensioni corrette
a = Φ_matrix \ y_weight
y_pred = Φ_matrix * a
error = norm(y_weight - y_pred)
return a, error
end
function plot_approximation(k)
a, error = approximate_and_error(k)
x_dense = range(minimum(x_height), maximum(x_height), length=1000)
y_preds_dense = [dot(a, Φ(x, k)) for x in x_dense]
p = scatter(x_height, y_weight, label="y2", markersize=5, color=:blue, legend=:topleft, xlabel="X Axis Label", ylabel="Y Axis Label", size=(600,400))
plot!(p, x_dense, y_preds_dense, label="y3 - Order $k", width=2, linecolor=:orange, linestyle=:solid)
title!("Grado $k - Errore: $(round(error; digits=2))")
return p
end
# Creazione delle sottotrame
plots_array = [plot_approximation(k) for k in [2,4,6,8,12,18]]
plot(plots_array..., layout=(2,3), size=(900,600))