有一份酒店数据,
收购(购入)酒店的价格 和 酒店面积 的关系
ECharts 效果展示 :
不加线性回归代码:
from flask import Flask,render_template
import pandas as pd
import settings
app = Flask(__name__)
app.config.from_object(settings)
file = pd.read_csv(r"D:\hotel\hotels.csv") # 文件存放地址
# 酒店收入价格与酒店面积的关系
# @app.route('/')
def hotel():
hh = file.loc[:,["Price in Millions","Square Meter"]].rename(columns={"Price in Millions":"price","Square Meter":"area"})
data = []
for idx,row in hh.iterrows():
data.append([row.area,row.price])
print(data)
if __name__ == '__main__':
hotel()
# app.run()
打印结果(传入ECharts的结果)
加入线性回归:
# 从sklearn库里导入
from sklearn.linear_model import LinearRegression
# 创建对象
lr = LinearRegression()
# 对上面的data进行后续操作
# data -> 准备好传入Echarts画散点图的格式
# 获取 x , y
data_x = [[xx[0]] for xx in data]
data_y = [[xx[1]] for xx in data]
lr.fit(data_x,data_y)
# 对 data_x 进行预测
temp = lr.predict(data_x)
# 创建一个空列表用于存放线性回归的数据
data_predict = []
# 遍历往创建的空列表存放数据
for i in range(len(temp)):
data_predict.append([data_x[i][0],temp[i][0]])
合并两个部分 :
from flask import Flask,render_template
from sklearn.linear_model import LinearRegression
import pandas as pd
import settings
app = Flask(__name__)
app.config.from_object(settings)
file = pd.read_csv(r"D:\hotel\hotels.csv")
lr = LinearRegression()
# 酒店收入价格与酒店面积的关系
@app.route('/')
def hotel():
hh = file.loc[:,["Price in Millions","Square Meter"]].rename(columns={"Price in Millions":"price","Square Meter":"area"})
data = []
for idx,row in hh.iterrows():
data.append([row.area,row.price])
# print(data)
data_x = [[xx[0]] for xx in data]
data_y = [[xx[1]] for xx in data]
lr.fit(data_x,data_y)
temp = lr.predict(data_x)
# print(temp)
data_y_predict = []
for i in range(len(temp)):
data_y_predict.append([data_x[i][0],temp[i][0]])
print(data_y_predict)
return render_template('hotel.html',data=data,data_y_predict=data_y_predict)
if __name__ == '__main__':
# hotel()
app.run()
最后在 画图的时候加上 一条线性回归的线就可了