Home > Net >  Increase the x-values when plotting in python
Increase the x-values when plotting in python

Time:04-11

I want to obtain a plot similar to this one. Currently I have obtained the following plot. I think I can achieve the first plot by increasing the resolution of the x-axis ranging [0 1] for the blue line. Here is the code to generate these plots.

x_plot_new = np.arange(0,1,0.0001)

fig = plt.figure(figsize=(10,5))
plt.scatter(x_train, t_train, c='black', label='Training Data')    
plt.plot(x_train, pred_train, label='Regression result M = 9')
plt.plot(x_n, function, c = 'red', label='f(x)')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.grid(True)
plt.legend(fontsize=16)
print(x_test)
print(x_train) 

All of the variables have shape (10,) except x_plot_new which has shape (10000,) and so I want to plot pred_train using x_plot_new.

Addendum on finding pred_train:

def basis_functions(X, L):
    w = np.empty(L 1)
    for x in X:
        p = [x ** (order) for order in range(L 1)]
        w = np.vstack((w, p))
    return w[1:]

phi_train = basis_functions(x_train, 9) #polynomial
w_p = np.linalg.pinv(phi_train)
w = w_p@t_train

pred_train = phi_train @ w

x_train, phi_train all have shape (10,)

CodePudding user response:

I don't know how you generate your pred_train variable but assuming you have a function that takes in x values and gives y values called something like reg_func you should be able to get results similar to the picture using

plt.plot(x_plot_new, reg_func(x_plot_new), label='Regression result M = 9')

Updated answer with code I used for plot

x = np.linspace(0,10,10) 
y = np.sin(x)   0.1 * rng.randn(10)  
phi_train = basis_functions(x, 9) #polynomial 
w_p = np.linalg.pinv(phi_train) 
w = w_p@y  
pred_train = phi_train @ w  
x_plot_new = np.arange(0,10,0.001)  
over_fit = basis_functions(x_plot_new, 9) 
over_fit_to_plot = over_fit @ w  
plt.scatter(x, y) 
plt.plot(x_plot_new, over_fit_to_plot)
  • Related