python - 线性回归的问题并总结
问题描述
我想创建一个线性回归模型图,显示每年的自行车销量在一个点上汇总,而不像现在分别有两个点。
这是我的代码:
from sklearn.linear_model import LinearRegression
from sklearn import datasets, linear_model
## Wzrost lub maleje zakup rowerow
## (Purchase of bicycles increases or decreases)
plot1 = df.groupby('Year')['Product_Category'].value_counts().rename('count').reset_index()
x = plot1['Year'].values.reshape(-1, 1)
y = plot1['count'].values.reshape(-1, 1)
# plot #
## linear ##
regr = linear_model.LinearRegression()
regr.fit(x, y)
y_pred = regr.predict(x_test)
#plot#
plt.scatter(x, y, color='black')
plt.plot(x, y, color='blue', linewidth=3)
这是我的情节:
解决方案
正如我从您的示例中可以理解的那样,这可能是一个解决方案,替换value_counts
为count
.
示例数据:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Year': [ 2019, 2019, 2020, 2021], 'Product_Category': ['a', 'b', 'c', 'd']})
print(df)
Year Product_Category
0 2019 a
1 2019 b
2 2020 c
3 2021 d
计数将返回:
plot1 = df.groupby('Year')['Product_Category'].count().rename('count').reset_index()
print(plot1)
Year count
0 2019 2
1 2020 1
2 2021 1
plot1 = df.groupby('Year')['Product_Category'].count().rename('count').reset_index()
#x,y#
x = plot1['Year'].values.reshape(-1, 1)
y = plot1['count'].values.reshape(-1, 1)
# plot #
#plot#
plt.scatter(x, y, color='black')
plt.plot(x, y, color='blue', linewidth=3)
推荐阅读
- python - XGBoost 决策树选择
- if-statement - TYPO3 Fluid elseif with && 条件
- java - Firebase Android 中的 Firebase 搜索嵌套对象搜索
- python - Django 管理面板不会呈现 CSS
- swift - 在结构内指定 Hashable 类型约束
- sql - 删除表中具有依赖外键的重复行
- node.js - 节点塞内卡猫鼬奇怪的行为
- angularjs - Angular UI Grid:如何用来自数据库/后端的真实数据填充下拉过滤器
- python - 如何为异步生成器提供来自 python.net 的事件
- javascript - 模拟红绿灯