记一次数据库的实战:
话不多说 直接开始:
题目是要我预测香港的1月份的疫情情况:
- 自己先在excel里面打好数据:
开始我们的敲代码的工程吧
首先导入头文件:
import tkinter
import tkinter.messagebox
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression # 线性回归
import datetime # 用于转换日期(最后发现还是做不起来)
我们这里不只是单单的一个数据库的调用与预测,我们加上tkinter的交互功能
- 先来看tkinter部分的模块:
class Mygui:
def __init__(self):
self.main_window=tkinter.Tk()
self.main_window.geometry('300x200+100+100')
self.bottom_frame=tkinter.Frame(self.main_window)
self.top_frame=tkinter.Frame(self.main_window)
self.middle_frame=tkinter.Frame(self.main_window)
button1=tkinter.Button(self.bottom_frame,text='预测一月份的香港疫情的输入病例',command=self.shuru,bg='red')
button2=tkinter.Button(self.bottom_frame,text='预测一月份的香港疫情的本地病例',command=self.local,bg='blue')
button3=tkinter.Button(self.bottom_frame,text='预测一月份的香港疫情的新增病例',command=self.huizong,bg='yellow')
button4=tkinter.Button(self.middle_frame,text='Quit',command=self.main_window.destroy)
label1=tkinter.Label(self.top_frame,text='关于预测香港一月份的疫情情况的报告')
button3.pack(side='bottom')
button2.pack(side='bottom')
button1.pack()
self.bottom_frame.pack(side='bottom')
button4.pack()
self.middle_frame.pack(side='top')
label1.pack(side='left')
self.top_frame.pack()
tkinter.mainloop()
这边的代码不做过多解释,都是比较基础的部分。
- 运行得到的一个tkinter的交互界面
下面的才是重头戏!
数据处理!
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
data=pd.read_excel('C:\\Users\\VanHurts\\Desktop\\期末作业\\python作业\\CSV\\香港疫情数据.xlsx')
data.index=data.iloc[:,0]
data=data.drop(['日期'],axis=1)
print(data)
model=LinearRegression()
##划分测试集和训练集7:3
m=data.shape[0]
train=data.iloc[:int(0.7*m),:]
test=data.iloc[int(0.7*m):,:]
for i in range(data.shape[1]):
train_y,train_x=train[train.columns[i]],train.drop([train.columns[i]],axis=1)
test_x,test_y=test.drop([test.columns[i]],axis=1),test[test.columns[i]]
model.fit(train_x,train_y)
predict=model.predict(test_x)
plt.plot(test_x.index,test_y,label='True',c='red') #x,y
plt.plot(test.index,predict,label='prdict',c='black') #图例注记
plt.title('predict {}'.format(str(train.columns[i]))) #表格标题
plt.show()