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, 0.2, 0.2, 0.2, 0.2,
1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3,
1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3,
2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1,
2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8]
# 線形回帰の実装
def linear_regression(x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
sum_xx = sum(xi ** 2 for xi in x)
m = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x ** 2)
b = (sum_y - m * sum_x) / n
return m, b
# 回帰分析
m, b = linear_regression(x, y)
# データポイントのプロット(plt.plot を使用)
plt.plot(x, y, 'bo', markersize=4, alpha=0.7, label='データポイント')
# 回帰直線の描画
min_x, max_x = min(x), max(x)
plt.plot([min_x, max_x], [m*min_x + b, m*max_x + b], color='red')
# グラフの設定
plt.xlabel('花弁の長さ (cm)')
plt.ylabel('花弁の幅 (cm)')
plt.title('アヤメの花弁: 長さと幅の関係')
# グラフの表示
plt.show()
77