首页 > 解决方案 > 在python中预测正弦波

问题描述

我正在尝试用 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根本不适合,因为它是用于分类的。什么方法更适合这个问题?

标签: pythonmachine-learningregressiontrigonometry

解决方案


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

阴谋

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)

推荐阅读