import matplotlib.pyplot as plt import random random.seed(0) n=100 x=[random.random()%10…
- User
import matplotlib.pyplot as plt import random random.seed(0)
n=100
x=[random.random()%10 for _ in range(n)]
y=[random.random()%8 for _ in range(n)]
n=5 x=[1,3,4,5.5,7 ] y=[3,5,6,8 ,11]
sumofx=0 sumofx2=0 sumofy=0 sumofxy=0
for i in range(n): sumofx = sumofx+x[i] sumofx2 = sumofx+x[i]**2 sumofy = sumofy+y[i] sumofxy = sumofxy+x[i]*y[i]
a1=(nsumofxy-sumofxsumofy)/(nsumofx2-sumofx**2) a0=(sumofy-a1sumofx)/n
plt.scatter(x,y, label='Data points' ) plt.plot([min(x), max(x)], [a0+a1min(x), a0+a1max(x)], color='red', label='Regression line')
plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.show()
このコードの回帰直線がうまく出力できません。コピペすると形が崩れてしまうのですが、総和や二乗の総和の計算などの入っているfor文は正常に動作しています。 どこを改修すればよいでしょうか?
- Assistant
提供されたコード内で、回帰直線がうまく出力されない原因の一つは、
sumofx2の計算です。sumofx2を計算する行を次のように修正する必要があります:sumofx2 = sumofx2+x[i]**2誤って
sumofx + x[i]**2としていて、これがsumofx2の計算式としては間違っています。修正することで、正しく二乗の和を計算し、その結果を用いて回帰直線のパラメーターを適切に導出できます。以下、修正後の完全なコードです:
import matplotlib.pyplot as plt import random random.seed(0) n=5 x=[1,3,4,5.5,7] y=[3,5,6,8,11] sumofx=0 sumofx2=0 sumofy=0 sumofxy=0 for i in range(n): sumofx += x[i] sumofx2 += x[i]**2 # 修正されました sumofy += y[i] sumofxy += x[i]*y[i] a1=(n*sumofxy-sumofx*sumofy)/(n*sumofx2-sumofx**2) a0=(sumofy-a1*sumofx)/n plt.scatter(x,y, label='Data points') plt.plot([min(x), max(x)], [a0+a1*min(x), a0+a1*max(x)], color='red', label='Regression line') plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.show()この修正により、データ点に基づいて適切に描画された回帰直線が表示されます。