如何解决使用预定义函数python拟合数据 PyTorch 曲线拟合函数 - Sin(2πx)从函数 Sin(2πx) 生成的数据添加了一些噪声我们的神经网络模型拟合的曲线,误差约为 6%
你能帮忙完成这样的任务吗? 我有一些数据。我知道数据必须符合一些预先定义的方程,例如 y=(1-x/1+x)。 我知道在 Origin 中可以做到这一点。可以用 使用 scikit-learn 或任何其他软件包?如果是,请您告知包装和确切功能。 非常感谢提前!!!!!!
解决方法
您可以使用 Scikit Learn 包轻松完成,您可以尝试多种模型。您可以查看这些,例如,它们展示了如何使用各种模型拟合曲线。
Curve Fitting with Bayesian Ridge Regression
Validation curves: plotting scores to evaluate models
OR
您还可以使用神经网络使用Tensorflow/PyTorch。下面我给出了一个使用 PyTorch 拟合曲线的例子。
PyTorch 曲线拟合(函数 - Sin(2πx))
import random
import torch
from torch import nn,optim
import numpy as np
# Generating data,that is X and Y values for the model to train on
X = torch.unsqueeze(torch.linspace(-1,1,100),dim=1).to(device) # x-axis values
y = (1-X/(1+X)) + torch.rand(X.size()) # adding a bit noise to the actual curve Sin(2πx),as real world is noisy and need our model to generalize
# some hyperparameters and global vars
seed = 1
random.seed(seed)
torch.manual_seed(seed)
N = 1000 # num_samples_per_class
D = 1 # dimensions
C = 1 # num_classes
H = 200 # num_hidden_units
learning_rate = 1e-2 # How big of a step the model should take towards solution *very important parameter for neural networks
lambda_l2 = 1e-5 # Regularizes the network
# Bulding the model
# nn package to create our linear model
# each Linear module has a weight and bias
model = nn.Sequential(
nn.Linear(D,H),nn.ReLU(),nn.Linear(H,C)
)
# nn package also has different loss functions.
# we use MSE loss for our regression task
criterion = torch.nn.MSELoss()
# we use the optim package to apply
# stochastic gradient descent for our parameter updates
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate,weight_decay=lambda_l2) # built-in L2
# Training
for t in range(2000):
# Feed forward to get the logits
y_pred = model(X)
# Compute the loss (MSE)
loss = criterion(y_pred,y)
print("[EPOCH]: %i,[LOSS or MSE]: %.6f" % (t,loss.item()))
display.clear_output(wait=True)
# zero the gradients before running
# the backward pass.
optimizer.zero_grad()
# Backward pass to compute the gradient
# of loss w.r.t our learnable params.
loss.backward()
# Update params
optimizer.step()
# After 2000 epochs/iterations of training
# Output: [EPOCH]: 1999,[LOSS or MSE]: 0.062801
从函数 Sin(2πx) 生成的数据(添加了一些噪声)
我们的神经网络模型拟合的曲线,误差约为 6%
注意:如果您不熟悉 PyTorch,您可以根据您的规范简单地更改上述代码中的 X、Y 值,它应该可以正常工作。您可以尝试不同的学习率、激活(例如双曲正切函数)等以获得更好的结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。