python中两个大数据样本的二次拟合函数进行预测

问题描述 投票:0回答:1

使用此 csv: https://docs.google.com/spreadsheets/d/1QbFIUE1AcFCOgDZH5K2vPColxXeBVDV-sJhS9On2BYY/edit?usp=sharing

我正在尝试编写一个程序来拟合二次函数来预测全球温度的变化 (y) 作为年 (x) 的函数。 有问题的函数是:

function

程序应创建一个显示训练示例和二次拟合的图 到数据。

这是我迄今为止尝试弄清楚基础知识的尝试。只需要转换一下即可:

import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt

#Generate 200 training examples

m = 200
x = np.random.randn(m)
y = np.random.randn(1) * x ** 2 + np.random.randn(1) * x + 
np.random.randn(1)
y = y + 0.4 * np.random.randn(m)

#Quadratic Fit

X = np.transpose([np.ones(m), x, x ** 2])
print(np.shape(X))
print(np.shape(y))

theta = inv(np.transpose(X) @X) @ np.transpose(X) @ y

plt.plot(x, y, 'bo')

xp = np.arange(-5, 5, 0.1)
yp = theta[0] + theta[1] * xp + theta[2] * xp ** 2

plt.plot(xp, yp, 'r-')
python function machine-learning prediction quadratic
1个回答
0
投票

这是您正在寻找的程序,使用批量梯度下降:

import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt

#Generate 200 training examples

m = 200
x = np.random.randn(m)
y = np.random.randn(1) * x ** 2 + np.random.randn(1) * x + np.random.randn(1)
y = y + 0.4 * np.random.randn(m)

theta = np.random.randn(3,1) # Start with random theta values

# Train the model for a couple of iterations and chose a learning rate
epochs = 60  # Train for 600 epochs if you wish to get almost identical result to normal ecuations result
learning_rate = 0.1
len_x = len(x)

for epoch in range(epochs):
    # Calculate the gradients of the LSE cost function with respect to each theta parameter

    theta_gradients = np.zeros((3,1))

    theta_gradients[2] = sum((label - theta[2] * value ** 2 - theta[1] * value - theta[0]) * (-value**2) for value,label in zip(x,y))/len_x
    theta_gradients[1] = sum((label - theta[2] * value ** 2 - theta[1] * value - theta[0]) * (-value) for value,label in zip(x,y))/len_x
    theta_gradients[0] = sum((label - theta[2] * value ** 2 - theta[1] * value - theta[0]) * (-1) for value,label in zip(x,y))/len_x


    # Update the theta parameters using descent

    for i in range(3):
        theta[i] = theta[i] - learning_rate * theta_gradients[i]


# At the end of the training you can plot the function with the new learned parameters


print("Learned thetas:", theta)

xp = np.arange(-5, 5, 0.1)
yp = theta[0] + theta[1] * xp + theta[2] * xp ** 2

plt.figure()
plt.plot(x, y, 'bo')
plt.plot(xp, yp, 'r-')
plt.title("Learned function")

#Quadratic Fit (for comparison)

X = np.transpose([np.ones(m), x, x ** 2])
# print(np.shape(X))
# print(np.shape(y))

theta = inv(np.transpose(X) @X) @ np.transpose(X) @ y
print("Normal thetas:", theta)

yp = theta[0] + theta[1] * xp + theta[2] * xp ** 2

plt.figure()
plt.plot(x, y, 'bo')
plt.plot(xp, yp, 'r-')
plt.title("Your function (normal ecuations result)")

该程序的工作方式如下:我们随机初始化 theta 参数,然后对模型进行多个 epoch 的训练。在每个时期,我们计算成本函数的梯度,考虑到每个参数 theta 的所有数据(不是最有效的方法,但它应该更容易理解)。然后我们使用梯度下降规则更新每个 θ。然后我们绘制预测函数。

我还保留了您使用所谓的“正规方程”计算出的最佳理论解,以进行比较。

我提供的学习率和纪元数足以适合您生成的每个数据集,但您可以使用它们进行实验,以防您希望以较慢的收敛速度(较长的训练时间)为代价获得更好的性能。 我还打印了模型学到的 theta,以及可以实现的最佳理论 theta,以进行比较。

如果您有任何问题,我很乐意回答。如果您对梯度或成本函数等概念的来源感兴趣,我建议您阅读一些有关逻辑回归的文献。

© www.soinside.com 2019 - 2024. All rights reserved.