# 多项式转换
def polynomial_basis_function(x, degree = 2):
"""
输入:
- x: tensor, 输入的数据,shape=[N,1]
- degree: int, 多项式的阶数
example Input: [[2], [3], [4]], degree=2
example Output: [[2^1, 2^2], [3^1, 3^2], [4^1, 4^2]]
注意:本案例中,在degree>=1时不生成全为1的一列数据;degree为0时生成形状与输入相同,全1的Tensor
输出:
- x_result: tensor
"""
if degree==0:
return torch.ones(shape = x.shape,dtype=torch.float32)
x_tmp = x
x_result = x_tmp
for i in range(2, degree+1):
x_tmp = torch.multiply(x_tmp,x) # 逐元素相乘
x_result = torch.concat((x_result,x_tmp),axis=-1)
return x_result
plt.rcParams['figure.figsize'] = (12.0, 8.0)
for i, degree in enumerate([0, 1, 3, 8]): # []中为多项式的阶数
model = Linear(degree)
X_train_transformed = polynomial_basis_function(X_train.reshape([-1,1]), degree)
X_underlying_transformed = polynomial_basis_function(X_underlying.reshape([-1,1]), degree)
model = optimizer_lsm(model,X_train_transformed,y_train.reshape([-1,1])) #拟合得到参数
y_underlying_pred = model(X_underlying_transformed).squeeze()
print(model.params)
# 绘制图像
plt.subplot(2, 2, i + 1)
plt.scatter(X_train, y_train, facecolor="none", edgecolor='#e4007f', s=50, label="train data")
plt.plot(X_underlying, y_underlying, c='#000000', label=r"$\sin(2\pi x)$")
plt.plot(X_underlying, y_underlying_pred, c='#f19ec2', label="predicted function")
plt.ylim(-2, 1.5)
plt.annotate("M={}".format(degree), xy=(0.95, -1.4))
#plt.legend(bbox_to_anchor=(1.05, 0.64), loc=2, borderaxespad=0.)
plt.legend(loc='lower left', fontsize='x-large')
plt.savefig('ml-vis3.pdf')
plt.show()报错TypeError Traceback (most recent call last)
Cell In[113], line 5
3 for i, degree in enumerate([0, 1, 3, 8]): # []中为多项式的阶数
4 model = Linear(degree)
----> 5 X_train_transformed = polynomial_basis_function(X_train.reshape([-1,1]), degree)
6 X_underlying_transformed = polynomial_basis_function(X_underlying.reshape([-1,1]), degree)
8 model = optimizer_lsm(model,X_train_transformed,y_train.reshape([-1,1])) #拟合得到参数
Cell In[112], line 15, in polynomial_basis_function(x, degree)
3 """
4 输入:
5 - x: tensor, 输入的数据,shape=[N,1]
(...)
11 - x_result: tensor
12 """
14 if degree==0:
---> 15 return torch.ones(shape = x.shape,dtype=torch.float32)
17 x_tmp = x
18 x_result = x_tmp
TypeError: ones() received an invalid combination of arguments - got (shape=torch.Size, dtype=torch.dtype, ), but expected one of:
* (tuple of ints size, *, tuple of names names, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
* (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)如何修改