gpt4 book ai didi

python - 用Python预测正弦波

转载 作者:行者123 更新时间:2023-11-30 09:16:02 27 4
gpt4 key购买 nike

我正在尝试用 Python 编写一个算法来预测正弦波的输出。例如,如果输入为 90(以度为单位),则输出为 1。

当我尝试线性回归时,输出非常糟糕。

[in]
import pandas as pd
from sklearn.linear_model import LinearRegression

dic = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360]
dc = [0, 0.5, 0.866, 1, .866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0]
test = [1, 10, 100]

df = pd.DataFrame(dic)
dfy = pd.DataFrame(dc)
test = pd.DataFrame(test)

clf = LinearRegression()
clf.fit(df, dfy)

[out]
[[0.7340967 ]
[0.69718681]
[0.32808791]]

而Logistic根本不适合,因为它是用于分类的。什么方法更适合解决这个问题?

最佳答案

这是使用您的数据和正弦函数的图形非线性拟合器。 numpy 正弦函数使用弧度,因此此处使用的正弦函数会重新缩放输入。我通过查看数据的散点图猜测了初始参数估计值,从接近 0.0 的 RMSE 和接近 1.0 的 R 平方来看,数据似乎没有噪声成分。

plot

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


dic = [0.0, 30.0, 60.0, 90.0, 120.0, 150.0, 180.0, 210.0, 240.0, 270.0, 300.0, 330.0, 360.0]
dc = [0.0, 0.5, 0.866, 1.0, 0.866, 0.5, 0.0, -0.5, -0.866, -1.0, -0.866, -0.5, 0.0]

# rename data to match previous example code
xData = dic
yData = dc


def func(x, amplitude, center, width):
return amplitude * numpy.sin(numpy.pi * (x - center) / width)


# these are estimated from a scatterplot of the data
initialParameters = numpy.array([-1.0, 180.0, 180.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)

# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')

# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = func(xModel, *fittedParameters)

# now the model as a line plot
axes.plot(xModel, yModel)

axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label

plt.show()
plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

关于python - 用Python预测正弦波,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55912403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com