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



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

我正试图弄清楚如何编写一个程序来拟合二次函数来预测全球温度的变化(y( 作为年份(x(的函数。有问题的功能是:

功能

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

这就是我迄今为止所做的一次尝试,以了解基本情况。只需要转换它:

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-')

这是您正在寻找的使用批处理梯度下降的程序。注意,我并没有把重点放在优化代码上,而是可读且易于理解:

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)) # Reinitialize the gradients
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
# The zip funtion creates an iterable object by merging x and y.
# Basically we are iterating through the whole data set for each computation.
# 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)")

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

我还保留了最好的理论解,你用所谓的";正规方程";,进行比较。

我提供的学习率和历元数量足以适合您生成的每个数据集,但您可以使用它们进行实验,以防您以较慢的收敛(较长的训练时间(为代价想要更好的性能。我还列举了该模型所学到的理论和所能达到的最佳理论进行比较。

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

最新更新