在 python 中绘图时增加 x 值

Increase the x-values when plotting in python

我想获得与此类似的情节one. Currently I have obtained the following plot。我想我可以通过增加蓝线的 x 轴范围 [0 1] 的分辨率来实现第一个图。这是生成这些图的代码。

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) 

所有变量的形状都是 (10,),除了 x_plot_new 的形状是 (10000,),所以我想使用 x_plot_new 绘制 pred_train

关于发现的附录 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都有形状(10,)

我不知道你是如何生成你的 pred_train 变量的,但假设你有一个接受 x 值并给出 y 值的函数,类似于 reg_func 你应该能够得到结果类似于图片使用

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

使用我用于绘图的代码更新了答案

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)