python - 如何在sklearn中拟合数据
问题描述
我想编写读取 csv 文件的代码,然后使用线性回归进行预测。
CSV 文件是这样的:
数学 | 物理 |
---|---|
17 | 15 |
16 | 12 |
18 | 19 |
我试试这段代码:
import pandas as pd
from sklearn.linear_model import LinearRegression
score_file = pd.read_csv('scores.csv')
math_score = score_file['math']
physic_score = score_file['physics']
cls = LinearRegression().fit(math_score,physic_score)
但它给了我这个错误:
如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)
解决方案
import pandas as pd
from sklearn.linear_model import LinearRegression
score_file = pd.read_csv('scores.csv')
# score_file = pd.DataFrame.from_dict(
# {'math': [17, 16, 18],
# 'physics': [15, 12, 19]})
physic_score = score_file['physics']
print(score_file.shape) # (3, 2)
print(physic_score.shape) # (3,)
# take care of the dimentions
cls = LinearRegression().fit(score_file,physic_score)
# this should be made with a test subdataset or so...
predictions = cls.predict(score_file)
print(predictions) # [15. 12. 19.]
推荐阅读
- ruby-on-rails - Rspec 测试在创建多态 has_many 关系时失败
- python-3.x - 如何使用计时器在 Cloud Functions 中运行 Python 代码
- postgresql - postgresql:测试 dblink 连接的触发器,如果不存在则建立
- python - 平均相邻值时通过numpy数组优化迭代
- linux - 为什么 LOAD 程序头的虚拟地址和 gdb 显示的运行时虚拟地址不同?
- awk - 使用 awk one liner 比较浮点数
- pytest - setup() 函数的 pytest 奇怪行为
- unicode - 为什么恢复的文件没有以前的符号?
- kentico - 如何在 C# Kentico 12 MVC 中获取别名路径/节点别名
- angular - 为什么离子物品不显示?