python - 多项式回归

标签 python artificial-intelligence linear-regression

我想知道是否有人可以帮助我了解如何将此代码(线性回归)更改为多项式回归。我尽量不使用太多预制功能,以确保我理解我在做什么。

    # Importing Necessary Libraries
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20.0, 10.0)

# Reading Data
data = pd.read_csv('test.csv')
print(data.shape)
data.head()
# Collecting X and Y
X = data['a'].values
Y = data['b'].values
# Mean X and Y
mean_x = np.mean(X)
mean_y = np.mean(Y)

# Total number of values
m = len(X)

# Using the formula to calculate b1 and b2
numer = 0
denom = 0
for i in range(m):
    numer += (X[i] - mean_x) * (Y[i] - mean_y)
    denom += (X[i] - mean_x) ** 2
b1 = numer / denom
b0 = mean_y - (b1 * mean_x)

# Print coefficients
print(b1, b0)
max_x = np.max(X) + 100
min_x = np.min(X) - 100

# Calculating line values x and y
x = np.linspace(min_x, max_x, 1000)
y = b0 + b1 * x

# Ploting Line
plt.plot(x, y, color='#58b970', label='Regression Line')
# Ploting Scatter Points
plt.scatter(X, Y, c='#ef5423', label='Scatter Plot')

plt.xlabel('a')
plt.ylabel('b')
plt.legend()
plt.show()

现在我想从此代码“升级”它,使其作为多项式回归,3 次 (ax^3 + bx² ...)。有人可以帮助我吗?提前致谢。

最佳答案

这是一个图形多项式拟合器的示例:

import numpy, matplotlib
import matplotlib.pyplot as plt

xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7, 0.0])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7, 0.1])

polynomialOrder = 2 # example quadratic

# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)

modelPredictions = numpy.polyval(fittedParameters, xData)
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('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 = numpy.polyval(fittedParameters, xModel)

    # 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 - 多项式回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54730030/

相关文章:

python - 如何使用 mongokit/pymongo 填充 wtform 选择字段?

python - 如何使用python复制和粘贴现有工作簿中的现有工作表?

python - 如何在 Python 中捕获和处理来自另一个应用程序的实时事件?

python - 值错误 : continuous-multioutput is not supported

python - 根据 SQL 查询的结果设置 python 变量

python - 如何使用 TensorFlow 和 python 在 MNIST 数据上创建 2 层神经网络

java - 在二维数组列表中深度优先搜索时如何解析 "OutOfMemoryError: Java heap space"?

java - 如何通过 dl4j 正确使用我的神经网络?

python - 线性回归预测值错误 : "ValueError: shapes (1,1) and (132,132) not aligned: 1 (dim 1) != 132 (dim 0)"

python - 在线性回归中获得非常高的值