在python中预测正弦波

时间:2019-04-30 00:26:26

标签: python machine-learning regression sine

我正在尝试用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根本不适合,因为它用于分类。哪种方法更适合此问题?

1 个答案:

答案 0 :(得分:0)

这里是使用数据和正弦函数的图形非线性拟合器。 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)