python散点图线性回归
时间: 2023-10-11 14:04:34 浏览: 165
要在Python中制作散点图和进行线性回归,你可以使用matplotlib和sklearn库。以下是一种实现方法:
首先,导入所需的库:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
然后,准备数据并绘制散点图:
x = np.array([2, 5, 8, 8, 13, 15, 17, 19, 21, 24])
y = np.array([12, 31, 45, 52, 79, 85, 115, 119, 135, 145])
plt.scatter(x, y)
plt.xlabel("battery")
plt.ylabel("KM")
plt.title("散点图")
plt.show()
接下来,建立线性回归模型并进行拟合:
regressor = LinearRegression()
regressor.fit(np.reshape(x, (-1, 1)), np.reshape(y, (-1, 1)))
打印拟合结果(参数):
print("斜率:", regressor.coef_)
print("截距:", regressor.intercept_)
最后,画出数据和拟合直线的图:
plt.scatter(x, y)
plt.plot(np.reshape(x, (-1, 1)), regressor.predict(np.reshape(x, (-1, 1))))
plt.xlabel("battery")
plt.ylabel("KM")
plt.title("拟合结果")
plt.show()
这样,你就可以在Python中绘制散点图和进行线性回归了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [python 编程 线性回归,散点图,拟合结果](https://blog.csdn.net/qq_42262610/article/details/124290573)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [Python机器学习——线性回归案例(一)](https://blog.csdn.net/lucky_shi/article/details/105186572)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文