???♂? 個(gè)人主頁(yè):@艾派森的個(gè)人主頁(yè)
???作者簡(jiǎn)介:Python學(xué)習(xí)者
?? 希望大家多多支持,我們一起進(jìn)步!??
如果文章對(duì)你有幫助的話,
歡迎評(píng)論 ??點(diǎn)贊???? 收藏 ??加關(guān)注+
目錄
一、項(xiàng)目介紹
1.1項(xiàng)目簡(jiǎn)介
1.2技術(shù)工具
1.3頁(yè)面概述?
二、項(xiàng)目步驟
2.1首頁(yè)模塊
2.2查看歷年數(shù)據(jù)板塊
2.3預(yù)測(cè)板塊
2.4app.py
三、項(xiàng)目總結(jié)
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-490451.html
一、項(xiàng)目介紹
1.1項(xiàng)目簡(jiǎn)介
? ? ? ? ?本項(xiàng)目使用Flask框架搭建基于機(jī)器學(xué)習(xí)的世界杯比賽預(yù)測(cè)系統(tǒng) (簡(jiǎn)易版)
其中關(guān)于Flask知識(shí)點(diǎn)可參考文章Flask全套知識(shí)點(diǎn)從入門到精通,學(xué)完可直接做項(xiàng)目
關(guān)于基于機(jī)器學(xué)習(xí)的世界杯比賽預(yù)測(cè)模型可參考文章基于決策樹(shù)算法構(gòu)建世界杯比賽預(yù)測(cè)模型?
整個(gè)項(xiàng)目分為以下幾個(gè)模塊:
- 1.首頁(yè)板塊
- 2.展示往屆數(shù)據(jù)板塊
- 3.預(yù)測(cè)球隊(duì)勝率板塊
項(xiàng)目文件框架如下:
其中manager.py為主程序,password.csv為存儲(chǔ)用戶賬號(hào)密碼的文件,lianjia是房租價(jià)格原始數(shù)據(jù)集,model.pkl是經(jīng)過(guò)機(jī)器學(xué)習(xí)算法訓(xùn)練出的模型。?
1.2技術(shù)工具
IDE編輯器:vscode
后端框架:Flask
前端框架:Bootstrap
1.3頁(yè)面概述?
運(yùn)行app.py程序后,瀏覽器打開(kāi)http://127.0.0.1:5000/
映入眼簾的就是首頁(yè)板塊,主要就是項(xiàng)目的名稱。
?點(diǎn)擊導(dǎo)航欄中的查看歷年數(shù)據(jù)頁(yè)面
?點(diǎn)擊導(dǎo)航欄中的預(yù)測(cè)勝率頁(yè)面
?在預(yù)測(cè)頁(yè)面輸入兩只球隊(duì)的名稱即可進(jìn)行預(yù)測(cè),比如我這里讓他預(yù)測(cè)阿根廷VS法國(guó)的勝率
輸入名稱后點(diǎn)擊預(yù)測(cè)出現(xiàn)以下預(yù)測(cè)結(jié)果
Chance for Argentina to win France is 48.31226915281593
Chance for France to win Argentina is 30.51025652600164
Chance for Argentina and France draw is 21.17747432118242?
第一行表示阿根廷贏法國(guó)的概率為48.31%
第二行表示法國(guó)贏阿根廷的概率為30.51%
第三行表示阿根廷和法國(guó)平局的概率為21.18%
二、項(xiàng)目步驟
2.1首頁(yè)模塊
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首頁(yè)</title>
<link rel="stylesheet" href="../static/bootstrap.min.css">
<link rel="stylesheet" href="../static/main.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" >首頁(yè)</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" href="{{url_for('display_data')}}">查看歷年數(shù)據(jù)</a>
<a class="nav-link" href="{{url_for('my_predict')}}">預(yù)測(cè)勝率</a>
</div>
</div>
</nav>
<h1 style="margin-top: 200px;margin-left: 230px;">基于機(jī)器學(xué)習(xí)算法的世界杯比賽預(yù)測(cè)系統(tǒng)</h1>
</div>
</body>
</html>
2.2查看歷年數(shù)據(jù)板塊
display_data.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>查看歷年數(shù)據(jù)</title>
<link rel="stylesheet" href="../static/bootstrap.min.css">
<link rel="stylesheet" href="../static/main.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="{{url_for('index')}}">首頁(yè)</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" href="{{url_for('display_data')}}">查看歷年數(shù)據(jù)</a>
<a class="nav-link" href="{{url_for('my_predict')}}">預(yù)測(cè)勝率</a>
</div>
</div>
</nav>
<div>
<section class="counts section-bg">
<div class="container">
<table class="table text-nowrap">
<tr class="text-center">
<td>Year</td>
<td>HostCountry</td>
<td>Winner</td>
<td>Second</td>
<td>Third</td>
<td>Fourth</td>
<td>GoalsScored</td>
<td>QualifiedTeams</td>
<td>MatchesPlayed</td>
</tr>
{% for data in datas %}
<tr class="text-center">
<td>{{ data.Year }}</td>
<td>{{ data.HostCountry }}</td>
<td>{{ data.Winner }}</td>
<td>{{ data.Second }}</td>
<td>{{ data.Third }}</td>
<td>{{ data.Fourth }}</td>
<td>{{ data.GoalsScored }}</td>
<td>{{ data.QualifiedTeams }}</td>
<td>{{ data.MatchesPlayed }}</td>
</tr>
{% endfor %}
</table>
</div>
</section><!-- End Counts Section -->
</div>
</div>
</body>
</html>
2.3預(yù)測(cè)板塊
predict.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>預(yù)測(cè)勝率</title>
<link rel="stylesheet" href="../static/bootstrap.min.css">
<link rel="stylesheet" href="../static/main.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="{{url_for('index')}}">首頁(yè)</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" href="{{url_for('display_data')}}">查看歷年數(shù)據(jù)</a>
<a class="nav-link active" href="{{url_for('my_predict')}}">預(yù)測(cè)勝率</a>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col col-lg-2">
</div>
<div class="col-md-auto">
<form action="/predict/" method="post">
<div class="form-group row">
<label for="inputPassword" class="col-sm-6 col-form-label">請(qǐng)輸入球隊(duì)1:</label>
<div class="col-sm-8">
<input type="text" placeholder="Uruguay/Italy/Brazil/..." name="team1" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-6 col-form-label">請(qǐng)輸入球隊(duì)2:</label>
<div class="col-sm-8">
<input type="text" placeholder="Uruguay/Italy/Brazil/..." name="team2" class="form-control">
</div>
</div>
<button style="margin-left: 10px;" type="submit" class="btn btn-primary">預(yù)測(cè)</button>
</form>
{% if error %}
<font color="red">{{ error }}</font>
{% endif %}
{% if prob1 %}
<font color="red">
預(yù)測(cè)的結(jié)果為:
</font>
<br>
<font color="red">
Chance for {{ team1 }} to win {{ team2 }} is {{ prob1 }}
</font>
<br>
<font color="red">
Chance for {{ team2 }} to win {{ team1 }} is {{ prob2 }}
</font>
<br>
<font color="red">
Chance for {{ team1 }} and {{ team2 }} draw is {{ prob3 }}
</font>
{% endif %}
</div>
<div class="col col-lg-2">
</div>
</div>
</div>
</div>
</body>
</html>
2.4app.py
from flask import Flask,render_template,views,request
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.svm import SVC
import warnings
warnings.filterwarnings('ignore')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/display_data')
def display_data():
WorldCupsSummary = pd.read_csv('WorldCupsSummary.csv')
datas = []
for item in WorldCupsSummary.values:
data = {}
data['Year'] = item[0]
data['HostCountry'] = item[1]
data['Winner'] = item[2]
data['Second'] = item[3]
data['Third'] = item[4]
data['Fourth'] = item[5]
data['GoalsScored'] = item[6]
data['QualifiedTeams'] = item[7]
data['MatchesPlayed'] = item[8]
datas.append(data)
return render_template('display_data.html',datas=datas)
class PredictView(views.MethodView):
def __jump(self,prob1=None,prob2=None,prob3=None,error=None,team1=None,team2=None):
return render_template('predict.html',prob1=prob1,prob2=prob2,prob3=prob3,error=error,team1=team1,team2=team2)
def get(self, result=None,error=None):
return self.__jump()
def post(self):
# 導(dǎo)入數(shù)據(jù)
matches = pd.read_csv('WorldCupMatches.csv')
players = pd.read_csv('WorldCupPlayers.csv')
cups = pd.read_csv('WorldCupsSummary.csv')
# 刪除缺失值
matches = matches.dropna()
players = players.dropna()
cups = cups.dropna()
# 用德國(guó)取代德國(guó)DR和德國(guó)FR,用俄羅斯取代蘇聯(lián)
def replace_name(df):
if(df['Home Team Name'] in ['German DR', 'Germany FR']):
df['Home Team Name'] = 'Germany'
elif(df['Home Team Name'] == 'Soviet Union'):
df['Home Team Name'] = 'Russia'
if(df['Away Team Name'] in ['German DR', 'Germany FR']):
df['Away Team Name'] = 'Germany'
elif(df['Away Team Name'] == 'Soviet Union'):
df['Away Team Name'] = 'Russia'
return df
matches = matches.apply(replace_name, axis='columns')
# 創(chuàng)建一個(gè)存儲(chǔ)足球隊(duì)的字典
team_name = {}
index = 0
for idx, row in matches.iterrows():
name = row['Home Team Name']
if(name not in team_name.keys()):
team_name[name] = index
index += 1
name = row['Away Team Name']
if(name not in team_name.keys()):
team_name[name] = index
index += 1
# 刪除不必要的列
dropped_matches = matches.drop(['Datetime', 'Stadium', 'Referee', 'Assistant 1', 'Assistant 2', 'RoundID',
'Home Team Initials', 'Away Team Initials', 'Half-time Home Goals', 'Half-time Away Goals',
'Attendance', 'City', 'MatchID', 'Stage'], 1)
# 計(jì)算每支球隊(duì)成為世界杯賽冠軍的次數(shù)
championships = cups['Winner'].map(lambda p: 'Germany' if p=='Germany FR' else p).value_counts()
# 加上“主隊(duì)冠軍”和“客場(chǎng)冠軍”:獲取世界杯冠軍的次數(shù)
dropped_matches['Home Team Championship'] = 0
dropped_matches['Away Team Championship'] = 0
def count_championship(df):
if(championships.get(df['Home Team Name']) != None):
df['Home Team Championship'] = championships.get(df['Home Team Name'])
if(championships.get(df['Away Team Name']) != None):
df['Away Team Championship'] = championships.get(df['Away Team Name'])
return df
dropped_matches = dropped_matches.apply(count_championship, axis='columns')
# 定義一個(gè)函數(shù)用于找出誰(shuí)贏了:主場(chǎng)勝:1,客場(chǎng)勝:2,平局:0
dropped_matches['Winner'] = '-'
def find_winner(df):
if(int(df['Home Team Goals']) == int(df['Away Team Goals'])):
df['Winner'] = 0
elif(int(df['Home Team Goals']) > int(df['Away Team Goals'])):
df['Winner'] = 1
else:
df['Winner'] = 2
return df
dropped_matches = dropped_matches.apply(find_winner, axis='columns')
# 將team_name字典中的團(tuán)隊(duì)名稱替換為id
def replace_team_name_by_id(df):
df['Home Team Name'] = team_name[df['Home Team Name']]
df['Away Team Name'] = team_name[df['Away Team Name']]
return df
teamid_matches = dropped_matches.apply(replace_team_name_by_id, axis='columns')
# 刪除不必要的列
teamid_matches = teamid_matches.drop(['Year', 'Home Team Goals', 'Away Team Goals'], 1)
X = teamid_matches[['Home Team Name', 'Away Team Name', 'Home Team Championship','Away Team Championship']]
X = np.array(X).astype('float64')
# 附加數(shù)據(jù):只需將“主隊(duì)名稱”替換為“客場(chǎng)球隊(duì)名稱”,將“主隊(duì)冠軍”替換為“客場(chǎng)球隊(duì)冠軍”,然后替換結(jié)果
_X = X.copy()
_X[:,0] = X[:,1]
_X[:,1] = X[:,0]
_X[:,2] = X[:,3]
_X[:,3] = X[:,2]
y = dropped_matches['Winner']
y = np.array(y).astype('int')
y = np.reshape(y,(1,850))
y = y[0]
_y = y.copy()
for i in range(len(_y)):
if(_y[i]==1):
_y[i] = 2
elif(_y[i] ==2):
_y[i] = 1
X = np.concatenate((X,_X), axis= 0)
y = np.concatenate((y,_y))
# 打亂數(shù)據(jù),然后拆分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集
X,y = shuffle(X,y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)
# 用SVM支持向量機(jī)模型進(jìn)行訓(xùn)練
svm_model = SVC(kernel='rbf', class_weight='balanced', probability=True)
svm_model.fit(X_train, y_train)
# 定義一個(gè)預(yù)測(cè)函數(shù),需要傳遞兩個(gè)球隊(duì)名稱,輸出兩個(gè)獲勝的概率
def prediction(team1, team2):
id1 = team_name[team1]
id2 = team_name[team2]
championship1 = championships.get(team1) if championships.get(team1) != None else 0
championship2 = championships.get(team2) if championships.get(team2) != None else 0
x = np.array([id1, id2, championship1, championship2]).astype('float64')
x = np.reshape(x, (1,-1))
_y = svm_model.predict_proba(x)[0]
return _y[1]*100,_y[2]*100,_y[0]*100
try:
team1 = request.form['team1']
team2 = request.form['team2']
# 預(yù)測(cè)比賽
prob1, prob2, prob3 = prediction(team1, team2)
return self.__jump(prob1=prob1,prob2=prob2,prob3=prob3,team1=team1,team2=team2)
except Exception as e:
print(EnvironmentError)
return self.__jump(error='輸入數(shù)據(jù)格式不對(duì),請(qǐng)重新輸入!')
app.add_url_rule('/predict/',view_func=PredictView.as_view('my_predict'))
if __name__ == '__main__':
app.run(debug=True)
三、項(xiàng)目總結(jié)
? ? ? ? 本次我們使用了Flask框架結(jié)合了基于機(jī)器學(xué)習(xí)的世界杯比賽預(yù)測(cè)模型,構(gòu)建了一個(gè)簡(jiǎn)易版基于機(jī)器學(xué)習(xí)的世界杯比賽預(yù)測(cè)系統(tǒng),整個(gè)項(xiàng)目還有很多地方可以優(yōu)化,比如頁(yè)面美化、模塊添加等等,這些就留給學(xué)習(xí)的小伙伴根據(jù)自身需求進(jìn)行創(chuàng)新升級(jí)!喜歡本項(xiàng)目的話就三連支持一下啦!
心得與體會(huì):
通過(guò)這次Python項(xiàng)目實(shí)戰(zhàn),我學(xué)到了許多新的知識(shí),這是一個(gè)讓我把書本上的理論知識(shí)運(yùn)用于實(shí)踐中的好機(jī)會(huì)。原先,學(xué)的時(shí)候感嘆學(xué)的資料太難懂,此刻想來(lái),有些其實(shí)并不難,關(guān)鍵在于理解。
在這次實(shí)戰(zhàn)中還鍛煉了我其他方面的潛力,提高了我的綜合素質(zhì)。首先,它鍛煉了我做項(xiàng)目的潛力,提高了獨(dú)立思考問(wèn)題、自我動(dòng)手操作的潛力,在工作的過(guò)程中,復(fù)習(xí)了以前學(xué)習(xí)過(guò)的知識(shí),并掌握了一些應(yīng)用知識(shí)的技巧等
在此次實(shí)戰(zhàn)中,我還學(xué)會(huì)了下面幾點(diǎn)工作學(xué)習(xí)心態(tài):
1)繼續(xù)學(xué)習(xí),不斷提升理論涵養(yǎng)。在信息時(shí)代,學(xué)習(xí)是不斷地汲取新信息,獲得事業(yè)進(jìn)步的動(dòng)力。作為一名青年學(xué)子更就應(yīng)把學(xué)習(xí)作為持續(xù)工作用心性的重要途徑。走上工作崗位后,我會(huì)用心響應(yīng)單位號(hào)召,結(jié)合工作實(shí)際,不斷學(xué)習(xí)理論、業(yè)務(wù)知識(shí)和社會(huì)知識(shí),用先進(jìn)的理論武裝頭腦,用精良的業(yè)務(wù)知識(shí)提升潛力,以廣博的社會(huì)知識(shí)拓展視野。
2)努力實(shí)踐,自覺(jué)進(jìn)行主角轉(zhuǎn)化。只有將理論付諸于實(shí)踐才能實(shí)現(xiàn)理論自身的價(jià)值,也只有將理論付諸于實(shí)踐才能使理論得以檢驗(yàn)。同樣,一個(gè)人的價(jià)值也是透過(guò)實(shí)踐活動(dòng)來(lái)實(shí)現(xiàn)的,也只有透過(guò)實(shí)踐才能鍛煉人的品質(zhì),彰顯人的意志。
3)提高工作用心性和主動(dòng)性。實(shí)習(xí),是開(kāi)端也是結(jié)束。展此刻自我面前的是一片任自我馳騁的沃土,也分明感受到了沉甸甸的職責(zé)。在今后的工作和生活中,我將繼續(xù)學(xué)習(xí),深入實(shí)踐,不斷提升自我,努力創(chuàng)造業(yè)績(jī),繼續(xù)創(chuàng)造更多的價(jià)值。
這次Python實(shí)戰(zhàn)不僅僅使我學(xué)到了知識(shí),豐富了經(jīng)驗(yàn)。也幫忙我縮小了實(shí)踐和理論的差距。在未來(lái)的工作中我會(huì)把學(xué)到的理論知識(shí)和實(shí)踐經(jīng)驗(yàn)不斷的應(yīng)用到實(shí)際工作中,為實(shí)現(xiàn)理想而努力。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-490451.html
?
到了這里,關(guān)于基于Flask+Bootstrap+機(jī)器學(xué)習(xí)的世界杯比賽預(yù)測(cè)系統(tǒng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!