我一直在学习python的机器学习,目前正在研究基础知识。我现在正在研究线性回归,并尝试在Python代码中实现一些数学公式。我成功地编写了基本公式,但现在我想在图形中获得通过X均值和Y均值的线
我试图查找网络,但每一个解释都使用了预测,x_train,y_train ect。我听说过,但还没到那儿。
import numpy as np
import matplotlib.pyplot as plt
X_positions = np.array([2,3,4,5,6])
y_positions = np.array([4,5,6,5,7])
plt.plot([X_positions], [y_positions], 'ro')
plt.axis([0,10,0,10])
X_means = X_positions.mean()
y_means = y_positions.mean()
plt.plot([X_means], [y_means], 'go')
plt.axis([0,10,0,10])
X_minus_X_means = X_positions - X_means
y_minus_y_means = y_positions - y_means
X_minus_X_means_squared = X_minus_X_means**2
X_minus_X_means_times_y_minus_y_means = X_minus_X_means * y_minus_y_means
m = sum(X_minus_X_means_times_y_minus_y_means) / sum(X_minus_X_means_squared)
b = y_means - m * X_means
答案 0 :(得分:0)
我建议您看一下此this tutorial,因为我从中偷了几行。
首先,您需要构造一个x值数组:
x = np.linspace(0, 10, 11) # constructs a numpy array of [0.0, 1.0, ... 10.0]
然后,您绘制函数:
plt.plot(x, m*x+b, linestyle='solid')
x是您的numpy数组,m是您计算的斜率,b是您计算的y截距
要显示图形,请执行以下操作:
plt.show()
要保存您的绘图,请执行以下操作:
plt.savefig("myplot.png")
在程序中:
import numpy as np
import matplotlib.pyplot as plt
X_positions = np.array([2,3,4,5,6])
y_positions = np.array([4,5,6,5,7])
plt.plot([X_positions], [y_positions], 'ro')
plt.axis([0,10,0,10])
X_means = X_positions.mean()
y_means = y_positions.mean()
plt.plot([X_means], [y_means], 'go')
plt.axis([0,10,0,10])
X_minus_X_means = X_positions - X_means
y_minus_y_means = y_positions - y_means
X_minus_X_means_squared = X_minus_X_means**2
X_minus_X_means_times_y_minus_y_means = X_minus_X_means * y_minus_y_means
m = sum(X_minus_X_means_times_y_minus_y_means) / sum(X_minus_X_means_squared)
b = y_means - m * X_means
x = np.linspace(0, 10, 10) # constructs a numpy array of [0.0, 1.0, ... 10.0]
plt.plot(x, m*x+b, linestyle='solid')
plt.show() # or use plt.savefig("filename.png")