「4結婚匏ず1葬儀」たたはモスクワ政府からのオヌプンデヌタの分析のための線圢回垰

Open Data Scienceなどの優れたデヌタサむ゚ンス資料にもかかわらず、私は心のI宎からスクラップを収集し続け、機械孊習スキルずデヌタ分析をれロから習埗した私の経隓を共有し続けおいたす。

前回の蚘事では、埌から血液で自分自身のデヌタを抜出する過皋で、分類によっおいく぀かの問題を調べたしたが、今は回垰の時が来たした。 今回は手元に照明がなかったので、他のギンプを削っおみるこずにしたした。

蚘事の 1぀で、囜内のオヌプンデヌタに目を向けるよう読者にキャンペヌンを行ったこずを思い出したす。 しかし、私は「消化のためのケフィア」たたは銬力のシャンプヌの広告の若い女性ではないので、私の良心は私がそれを経隓せずに䜕かをアドバむスするこずを蚱可したせんでした。

どこから始めたすか もちろん、ロシア政府からの公開デヌタにより、そこには党䜓の省がありたす。 ロシア政府の公開デヌタに関する私の知り合いは、この蚘事のむラストずほが同じでした。 いいえ、ノヌビヌりレンゎむにあるシネマホヌルの登録やトゥヌラにあるアむススケヌトリンクのレンタル機噚のリストにたったく興味がないわけではありたせん。これらは回垰タスクには適しおいたせん。

調べおみるず、ロシア連邊政府のODのサむトで䟡倀のあるものを芋぀けるこずができるず思いたすが、それほど簡単ではありたせん。

たた、埌で財務省のデヌタを残すこずにしたした。

おそらく、私はモスクワ政府の公開デヌタが奜きだったので、そこでいく぀かの朜圚的な問題を調べ、最終的にモスクワの垂民の地䜍の行為の登録に関する情報を幎ごずに遞択したした

線圢回垰の分野で最小限のスキルを適甚しお埗られたものは、 GitHubで簡単に確認できたす。もちろん、猫の䞋を芋るこずができたす。



UPD远加セクション-「ボヌナス」

はじめに



い぀ものように、蚘事の冒頭で、この蚘事を理解するために必芁なスキルに぀いおお話したす。
以䞋が必芁になりたす。


デヌタ分析ず機械孊習の分野にたったく慣れおいない堎合は、シリヌズの以前の蚘事をフォロヌした順に芋おください。各蚘事は熱心に曞かれおおり、デヌタサむ゚ンスに時間を費やすべきかどうかを理解できたす。

以䞋のネタバレの䞋に以前に準備されたすべおの蚘事

その他のサむクル蚘事
1.基本を孊ぶ

2.最初のスキルを緎習したす


さお、前に玄束したように、このシリヌズの蚘事はコンテンツで完了したす。

内容

パヌトI「結婚-靱皮靎を履かないでください」-受信および䞻芁なデヌタ分析。
パヌトII「フィヌルドの戊士ではない」-1単䜍での回垰
パヌトIII「1぀の頭は良いが、はるかに良い」-正則化によるいく぀かの理由での回垰
パヌトIV「すべおが金ではない」-機胜の远加
パヌトV「新しいカフタンをカットし、叀いカフタンを詊しおみおください」-トレンド予枬
ボヌナス-月ぞのアプロヌチが異なるため、粟床が向䞊したす

それでは、タスクに移りたしょう。 私たちの目暙は、線圢回垰の基本的な手法を実蚌し、予枬するものを自分で決定するのに十分なデヌタセットを掘り䞋げるこずです。

今回は簡朔になりたすが、線圢回垰のみを考慮するこずでトピックから逞​​脱するこずはありたせん他のメ゜ッドの存圚に぀いおはおそらく知っおいたす 

パヌトI 「結婚する-頑固な靎を履かないでください」-受信ず䞀次デヌタ分析


残念ながら、モスクワ政府の公開デヌタは、マむストリヌトプログラムの矎化に費やされた予算ほど広倧で無限ではありたせんが、それでも䟡倀のあるものを芋぀けるこずができたした。

垂民的地䜍の行為の登録のダむナミクスは私たちに非垞に適しおいたす。

これは、結婚匏、出生、芪子関係、死亡、名前の倉曎などのデヌタを含む、月ごずに分類されたほが100のレコヌドです。
回垰の問題を解決するには非垞に適しおいたす。

すべおのコヌドはGitHubでホストされたす
たあ、郚分的に、私たちは今それを準備しおいたす。

最初に、ラむブラリをむンポヌトしたす。

import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn import linear_model import warnings warnings.filterwarnings('ignore') %matplotlib inline 

次に、デヌタをロヌドしたす。 Pandasラむブラリを䜿甚するず、リモヌトサヌバヌからファむルをダりンロヌドできたす。これは、通垞、ペヌゞリダむレクトアルゎリズムがポヌタルで倉曎されないずいう条件で、䞀般的には玠晎らしいこずです。

コヌドのダりンロヌドリンクが機胜しないこずを願っおいたす。機胜しなくなった堎合は、曎新できるように「PM」に曞き蟌んでください

 #download df = pd.read_csv('https://op.mos.ru/EHDWSREST/catalog/export/get?id=230308', compression='zip', header=0, encoding='cp1251', sep=';', quotechar='"') #look at the data df.head(12) 

デヌタを芋おみたしょう
IDglobal_id幎月StateRegistrationOfBirthStateRegistrationOfDeathStateRegistrationOfMarriageStateRegistrationOfDivorceStateRegistrationOfPaternityExaminationStateRegistrationOfAdoptionStateRegistrationOfNameChange総数
13759165820101月9206104304997330212419549129762
23759165920102月906095734873293713269763928505
3375916602010行進109341052836424361164414771731973
43759166120104月10140950196983943153012864235572
53759166220105月945794823726355413979649228204
66235381220106月11253952991483666157013055635852
76235381320107月1147714340124733675156812356444220
86235381420108月1030215016108823496151213457841920
96235381620109月101409573107363738148010168636454
1062353817201010月1077693508862389915048968735167
1162353818201011月1029390916080392313559756831407
1262353819201012月10600966460234145155612468132793


月に関するデヌタを䜿甚する堎合は、モデルの理解可胜な圢匏に倉換する必芁がありたす。scikit-learnには独自のメ゜ッドがありたすが、信頌性のために倚くの䜜業がないため手䜜業で行い、同時にIDを持぀いく぀かの圹に立たない列を削陀したすゎミ。

泚この堎合、Monthカラムには、 ワンホットコヌディングを適甚する方が正しいず思いたすが、この堎合、予枬の品質にはあたり関心がないため、そのたたにしおおきたす。
UPD抵抗できず、 ボヌナスセクションに調敎オプションを远加したした


 #code months d={'':1, '':2, '':3, '':4, '':5, '':6, '':7, '':8, '':9, '':10, '':11, '':12} df.Month=df.Month.map(d) #delete some unuseful columns df.drop(['ID','global_id','Unnamed: 12'],axis=1,inplace=True) #look at the data df.head(12) 

衚圢匏のビュヌがすべおのナヌザヌに察しお開くかどうかわからないので、画像を䜿甚しおデヌタを芋おみたしょう。



テヌブルのどの列が互いに線圢に䟝存しおいるかが明らかになるペア図を䜜成したす。 ただし、すぐにすべおのデヌタを怜蚎するわけではないため、埌で远加するものがあるため、最初にデヌタの䞀郚を削陀したす。
pandas Dataframeから列の䞀郚を遞択「削陀」する簡単な方法は、必芁な列を遞択するこずです。

 columns_to_show = ['StateRegistrationOfBirth', 'StateRegistrationOfMarriage', 'StateRegistrationOfPaternityExamination', 'StateRegistrationOfDivorce','StateRegistrationOfDeath'] data=df[columns_to_show] 


さお、これでスケゞュヌルを䜜成できたす。

  grid = sns.pairplot(data) 



銬を干し草の山の重量ず1か月の平均気圧ず比范しないように、特性をスケヌリングするこずをお勧めしたす。
私たちの堎合、すべおのデヌタは同じ倀登録された行為の数で衚瀺されたすが、スケヌリングの倉化を芋おみたしょう。

 # change scale of features scaler = MinMaxScaler() df2=pd.DataFrame(scaler.fit_transform(df)) df2.columns=df.columns data2=df2[columns_to_show] grid2 = sns.pairplot(data2) 



ほずんど䜕もありたせんが、信頌性のために、スケヌルされたデヌタをずりたす。

パヌトII 「フィヌルドにいるだけでは戊士ではありたせん」-1単䜍で回垰


写真を芋お、最善の方法は、StateRegistrationOfBirthずStateRegistrationOfPaternityExaminationの2぀のサむンの関係を盎線で蚘述するこずです。これは䞀般にそれほど驚くこずではありたせん「パタニティヌ」がチェックされるほど、子䟛が登録される頻床が高くなりたす。
デヌタを準備したす。぀たり、2぀の列の笊号ず目的関数を遞択し、既補のラむブラリを䜿甚しお、デヌタをトレヌニングおよび制埡サンプルに分割したすデヌタを目的の圢匏にするには、コヌドの最埌の操䜜が必芁でした

 X = data2['StateRegistrationOfBirth'].values y = data2['StateRegistrationOfPaternityExamination'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) X_train=np.reshape(X_train,[X_train.shape[0],1]) y_train=np.reshape(y_train,[y_train.shape[0],1]) X_test=np.reshape(X_test,[X_test.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) 

時系列にリンクする明確な可胜性にもかかわらず、デモンストレヌションの目的のために、デヌタを時間に関係なく単にレコヌドのセットず芋なすこずに泚意するこずが重芁です。

モデルデヌタを "フィヌド"しお、属性の係数を調べ、R ^ 2決定係数を䜿甚しおモデルを近䌌する粟床を評䟡したす。

 #teach model and get predictions lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_test,y_test)) 

それはあたりうたくいきたせんでしたが、䞀方で「掚枬で突く」よりもはるかに良いです

Coefficients: [[ 0.78600258]]
Score: 0.611493944197



最初にトレヌニングデヌタでチャヌトでこれを芋おみたしょう

 plt.scatter(X_train, y_train, color='black') plt.plot(X_train, lr.predict(X_train), color='blue', linewidth=3) plt.xlabel('StateRegistrationOfBirth') plt.ylabel('State Registration OfPaternity Examination') plt.title="Regression on train data" 



そしお今、コントロヌルに

 plt.scatter(X_test, y_test, color='black') plt.plot(X_test, lr.predict(X_test), color='green', linewidth=3) plt.xlabel('StateRegistrationOfBirth') plt.ylabel('State Registration OfPaternity Examination') plt.title="Regression on test data" 



パヌトIII 「1぀の頭は良いが、はるかに良い」-正則化によるいく぀かの理由での回垰



さらに面癜くするために、別の目的関数を遞択したしょう。これは、明らかに特城にそれほど線圢に䟝存しおいたせん。
蚘事のタむトルに合わせお、目的関数ずしお結婚登録を遞択したす。
そしお、ペアの図蚘号の写真のセットから残りのすべおの列を䜜成したす。

 #get main data columns_to_show2=columns_to_show.copy() columns_to_show2.remove("StateRegistrationOfMarriage") #get data for a model X = data2[columns_to_show2].values y = data2['StateRegistrationOfMarriage'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) y_train=np.reshape(y_train,[y_train.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) 

最初に、線圢回垰モデルのみをトレヌニングしたす。

 lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_test,y_test)) 

過去の堎合よりも結果が少し悪くなりたす驚くこずではありたせん

Coefficients: [[-0.03475475 0.97143632 -0.44298685 -0.18245718]]
Score: 0.38137432065


再トレヌニングおよび/たたは機胜遞択ず戊うために、通垞、線圢回垰モデルずずもに正則化メカニズムが䜿甚されたす。この蚘事では、なげなわメカニズム L1-正則化 を怜蚎したす。

アルファ正則化係数が高いほど、モデルは、回垰方皋匏のいく぀かの係数をれロにするたで、属性の倧きな倀をより積極的に现かくしたす。

 #let's look at the different alpha parameter: #large Rid=linear_model.Lasso (alpha = 0.01) Rid.fit(X_train, y_train) print(' Appha:', Rid.alpha) print(' Coefficients:', Rid.coef_) print(' Score:', Rid.score(X_test,y_test)) #Small Rid=linear_model.Lasso (alpha = 0.000000001) Rid.fit(X_train, y_train) print('\n Appha:', Rid.alpha) print(' Coefficients:', Rid.coef_) print(' Score:', Rid.score(X_test,y_test)) #Optimal (for these test data) Rid=linear_model.Lasso (alpha = 0.00025) Rid.fit(X_train, y_train) print('\n Appha:', Rid.alpha) print(' Coefficients:', Rid.coef_) print(' Score:', Rid.score(X_test,y_test)) 

ここで私はここで悪いこずをしおいるので、テストデヌタに正則化係数を調敎したこずに泚意しおください、実際にはこれを行うべきではありたせんが、実蚌するのは問題ありたせん。

出力を芋おみたしょう。

Appha: 0.01
Coefficients: [ 0. 0.46642996 -0. -0. ]
Score: 0.222071102783

Appha: 1e-09
Coefficients: [-0.03475462 0.97143616 -0.44298679 -0.18245715]
Score: 0.38137433837

Appha: 0.00025
Coefficients: [-0.00387233 0.92989507 -0.42590052 -0.17411615]
Score: 0.385551648602


この堎合、正則化されたモデルでは品質が倧幅に向䞊するこずはありたせん。機胜を远加しおください。

パヌトIV 「すべおがゎヌルドではない」-機胜を远加


明らかに圹に立たない「登録総数」の蚘号を远加したす。なぜそれが明らかなのですか さあ、自分で芋おください。

 columns_to_show3=columns_to_show2.copy() columns_to_show3.append("TotalNumber") columns_to_show3 X = df2[columns_to_show3].values # y hasn't changed X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) y_train=np.reshape(y_train,[y_train.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) 

たず、正芏化せずに結果を芋おみたしょう。

 lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_test,y_test)) 

Coefficients: [[-0.45286477 -0.08625204 -0.19375198 -0.63079401 1.57467774]]
Score: 0.999173764473


狂おう ほが100の粟床
この属性はどのように圹に立たないのでしょうか
たあ、賢明に考えおみたしょう、私たちの結婚数は合蚈に含たれおいるので、他の兆候に関する情報があれば、粟床は100に近いです。 実際には、これは特に有甚ではありたせん。

なげなわに移りたしょう
たず、小さな正則化係数を遞択したす。

 #Optimal (for these test data) Rid=linear_model.Lasso (alpha = 0.00015) Rid.fit(X_train, y_train) print('\n Appha:', Rid.alpha) print(' Coefficients:', Rid.coef_) print(' Score:', Rid.score(X_test,y_test)) 

Appha: 0.00015
Coefficients: [-0.44718703 -0.07491507 -0.1944702 -0.62034146 1.55890505]
Score: 0.999266251287

さお、䜕も倧きな倉化はありたせん。面癜くないので、増やした堎合にどうなるか芋おみたしょう。

 #large Rid=linear_model.Lasso (alpha = 0.01) Rid.fit(X_train, y_train) print('\n Appha:', Rid.alpha) print(' Coefficients:', Rid.coef_) print(' Score:', Rid.score(X_test,y_test)) 

Appha: 0.01
Coefficients: [-0. -0. -0. -0.05177979 0.87991931]
Score: 0.802210158982


したがっお、モデルではほずんどすべおの蚘号が圹に立たないず芋なされ、レコヌドの総数の蚘号が最も有甚なたたであるこずがわかりたす。そのため、突然1-2個の蚘号のみを䜿甚する必芁が生じた堎合、損倱を最小限に抑えるために䜕を遞択するかがわかりたす。

奜奇心から、レコヌドの総数だけで結婚登録の割合を説明できるこずを芋おみたしょう。

 X_train=np.reshape(X_train[:,4],[X_train.shape[0],1]) X_test=np.reshape(X_test[:,4],[X_test.shape[0],1]) lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_train,y_train)) 

Coefficients: [ 1.0571131]
Score: 0.788270672692

たあ、悪くはないが、客芳的に他の兆候を考慮するよりも少ない
グラフを芋おみたしょう

 # plot for train data plt.figure(figsize=(8,10)) plt.subplot(211) plt.scatter(X_train, y_train, color='black') plt.plot(X_train, lr.predict(X_train), color='blue', linewidth=3) plt.xlabel('Total Number of Registration') plt.ylabel('State Registration Of Marriage') plt.title="Regression on train data" # plot for test data plt.subplot(212) plt.scatter(X_test, y_test, color='black') plt.plot(X_test, lr.predict(X_test), '--', color='green', linewidth=3) plt.xlabel('Total Number of Registration') plt.ylabel('State Registration Of Marriage') plt.title="Regression on test data" 



元のデヌタセットに別の圹に立たない属性を远加しおみたしょう。
名前倉曎の状態登録では、独立しおモデルを構築し、この属性が説明するデヌタ量を確認できたす䞀蚀。
そしお、すぐにデヌタを遞択し、叀い4぀の暙識でモデルをトレヌニングしたす。

 columns_to_show4=columns_to_show2.copy() columns_to_show4.append("StateRegistrationOfNameChange") X = df2[columns_to_show4].values # y hasn't changed X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) y_train=np.reshape(y_train,[y_train.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_test,y_test)) 

Coefficients: [[ 0.06583714 1.1080889 -0.35025999 -0.24473705 -0.4513887 ]]
Score: 0.285094398157

この症状は私たちを台無しにするだけなので、正則化は詊みたせん;基本的には䜕も倉曎したせん。

最埌に䟿利な機胜を遞択したしょう。

誰もが結婚匏の暑い季節倏ず初秋があり、静かな季節冬があるこずを知っおいたす。

ちなみに、5月には結婚匏がほずんどないこずに驚きたした。

 #get data columns_to_show5=columns_to_show2.copy() columns_to_show5.append("Month") #get data for model X = df2[columns_to_show5].values # y hasn't changed X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) y_train=np.reshape(y_train,[y_train.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) #teach model and get predictions lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_) print('Score:', lr.score(X_test,y_test)) 

Coefficients: [[-0.10613428 0.91315175 -0.55413198 -0.13253367 0.28536285]]
Score: 0.472057997208

質の向䞊、そしお最も重芁なこずは、すべおが健党な論理に察応しおいるこずです。

パヌトv 「新しいカフタンをカットし、叀いものを詊しおみおください」-トレンド予枬


おそらく最埌に残したこずは、トレンドを予枬するためのツヌルずしお線圢回垰を芋るこずです。 前の章では、デヌタをランダムに取埗したした。぀たり、党時間範囲のデヌタがトレヌニングセットに分類されたした。 今回は、デヌタを過去ず未来に分割し、䜕かを予枬できるかどうかを確認したす

䟿宜䞊、2010幎1月からの期間を月単䜍で怜蚎したす。このため、デヌタを倉換する単玔な匿名関数を䜜成したす。その結果、幎列を月数で眮き換えたす。

2016幎たでデヌタの調査を行い、2016幎から始たるすべおが私たちの未来です。

 #get data df3=df.copy() #get new column df3.Year=df.Year.map(lambda x: (x-2010)*12)+df.Month df3.rename(columns={'Year': 'Months'}, inplace=True) #get data for model X=df3[columns_to_show5].values y=df3['StateRegistrationOfMarriage'].values train=[df3.Months<=72] test=[df3.Months>72] X_train=X[train] y_train=y[train] X_test=X[test] y_test=y[test] y_train=np.reshape(y_train,[y_train.shape[0],1]) y_test=np.reshape(y_test,[y_test.shape[0],1]) #teach model and get predictions lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_[0]) print('Score:', lr.score(X_test,y_test)) 

Coefficients: [ 2.60708376e-01 1.30751121e+01 -3.31447168e+00 -2.34368684e-01
2.88096512e+02]
Score: 0.383195050367

このようなデヌタの内蚳を芋るずわかるように、粟床はいくぶん䜎䞋しおいたすが、予枬の品質は空の指よりも優れおいたす。
グラフを芋お確認しおください。

 plt.figure(figsize=(9,23)) # plot for train data plt.subplot(311) plt.scatter(df3.Months.values[train], y_train, color='black') plt.plot(df3.Months.values[train], lr.predict(X_train), color='blue', linewidth=2) plt.xlabel('Months (from 01.2010)') plt.ylabel('State Registration Of Marriage') plt.title="Regression on train data" # plot for test data plt.subplot(312) plt.scatter(df3.Months.values[test], y_test, color='black') plt.plot(df3.Months.values[test], lr.predict(X_test), color='green', linewidth=2) plt.xlabel('Months (from 01.2010)') plt.ylabel('State Registration Of Marriage') plt.title="Regression (prediction) on test data" # plot for all data plt.subplot(313) plt.scatter(df3.Months.values[train], y_train, color='black') plt.plot(df3.Months.values[train], lr.predict(X_train), color='blue', label='train', linewidth=2) plt.scatter(df3.Months.values[test], y_test, color='black') plt.plot(df3.Months.values[test], lr.predict(X_test), color='green', label='test', linewidth=2) plt.title="Regression (prediction) on all data" plt.xlabel('Months (from 01.2010)') plt.ylabel('State Registration Of Marriage') #plot line for link train to test plt.plot([72,73], lr.predict([X_train[-1],X_test[0]]) , color='magenta',linewidth=2, label='train to test') plt.legend() 



チャヌトでは、過去は青で衚瀺され、未来は緑で衚瀺され、バンドルは玫で衚瀺されたす。
したがっお、モデルがポむントを䞍完党に蚘述しおいるこずは明らかですが、少なくずも季節のパタヌンを考慮しおいたす。

したがっお、将来、利甚可胜なデヌタによるず、モデルは結婚を登録するずいう芳点から、䜕らかの圢で私たちを方向づけるこずができるず期埅できたす。

この蚘事の範囲を超えたトレンド分析甚のより高床なツヌルがありたすが私の意芋では、デヌタサむ゚ンスの初期スキル

おわりに


さお、回垰埩元の問題を調査したした。囜の州構造のオヌプンデヌタポヌタルで他の䟝存関係を探すこずをお勧めしたす。興味深い䟝存関係が芋぀かるかもしれたせん。 「チャレンゞ」ずしお、ベラルヌシ共和囜opendata.byのオヌプンデヌタポヌタルで䜕かを掘り䞋げるこずをお勧めしたす。
写真の最埌に、 アレクサンダヌ・グリゎリ゚ノィッチず蚘者ずのコミュニケヌションず䞍快な質問ぞの回答に基づいおいたす。




ボヌナス-月ぞのアプロヌチが異なるため、粟床が向䞊したす


同僚は、予枬の品質を改善するための掚奚事項を含む有甚なコメントを残したした。

芁するに、すべおの提案は、すべおを簡玠化するために、「月」列を誀っお゚ンコヌドしたずいう事実に垰着したしたこれは本圓にそうです。 これを2぀の方法で改善しようずしたす。

オプション1-ワンホットコヌディング。各月の倀に察しお独自の特性が䜜成される堎合。

開始するには、線集せずに゜ヌスプレヌトをダりンロヌドしおください

 df_base = pd.read_csv('https://op.mos.ru/EHDWSREST/catalog/export/get?id=230308', compression='zip', header=0, encoding='cp1251', sep=';', quotechar='"') 

次に、pandasデヌタフレヌムラむブラリget_dummies関数に実装されたワンホットコヌディングを適甚し、䞍芁な列を削陀し、モデルのトレヌニングずグラフの描画を再開したす。

 #get data for model df4=df_base.copy() df4.drop(['Year','StateRegistrationOfMarriage','ID','global_id','Unnamed: 12','TotalNumber','StateRegistrationOfNameChange','StateRegistrationOfAdoption'],axis=1,inplace=True) df4=pd.get_dummies(df4,prefix=['Month']) X=df4.values X_train=X[train] X_test=X[test] #teach model and get predictions lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_[0]) print('Score:', lr.score(X_test,y_test)) # plot for all data plt.scatter(df3.Months.values[train], y_train, color='black') plt.plot(df3.Months.values[train], lr.predict(X_train), color='blue', label='train', linewidth=2) plt.scatter(df3.Months.values[test], y_test, color='black') plt.plot(df3.Months.values[test], lr.predict(X_test), color='green', label='test', linewidth=2) plt.title="Regression (prediction) on all data" plt.xlabel('Months (from 01.2010)') plt.ylabel('State Registration Of Marriage') #plot line for link train to test plt.plot([72,73], lr.predict([X_train[-1],X_test[0]]) , color='magenta',linewidth=2, label='train to test') 

ゲット

Coefficients: [ 2.18633008e-01 -1.41397731e-01 4.56991414e-02 -5.17558633e-01
4.48131002e+03 -2.94754108e+02 -1.14429758e+03 3.61201946e+03
2.41208054e+03 -3.23415050e+03 -2.73587261e+03 -1.31020899e+03
4.84757208e+02 3.37280689e+03 -2.40539320e+03 -3.23829714e+03]
Score: 0.869208071831




品質が倧幅に向䞊したした

オプション2-タヌゲット゚ンコヌディング、毎月トレヌニングサンプルで今月の目的関数の平均倀を゚ンコヌドしたす roryorangepantsに感謝

 #get data for pandas data frame df5=df_base.copy() d=dict() #get we obtain the mean value of Registration Of Marriages by months on the training data for mon in df5.Month.unique(): d[mon]=df5.StateRegistrationOfMarriage[df5.Month.values[train]==mon].mean() #d+={} df5['MeanMarriagePerMonth']=df5.Month.map(d) df5.drop(['Month','Year','StateRegistrationOfMarriage','ID','global_id','Unnamed: 12','TotalNumber', 'StateRegistrationOfNameChange','StateRegistrationOfAdoption'],axis=1,inplace=True) #get data for model X=df5.values X_train=X[train] X_test=X[test] #teach model and get predictions lr = linear_model.LinearRegression() lr.fit(X_train, y_train) print('Coefficients:', lr.coef_[0]) print('Score:', lr.score(X_test,y_test)) # plot for all data plt.scatter(df3.Months.values[train], y_train, color='black') plt.plot(df3.Months.values[train], lr.predict(X_train), color='blue', label='train', linewidth=2) plt.scatter(df3.Months.values[test], y_test, color='black') plt.plot(df3.Months.values[test], lr.predict(X_test), color='green', label='test', linewidth=2) plt.title="Regression (prediction) on all data" plt.xlabel('Months (from 01.2010)') plt.ylabel('State Registration Of Marriage') #plot line for link train to test plt.plot([72,73], lr.predict([X_train[-1],X_test[0]]) , color='magenta',linewidth=2, label='train to test')- 

取埗するもの

Coefficients: [ 0.16556761 -0.12746446 -0.03652408 -0.21649349 0.96971467]
Score: 0.875882918435




品質の点で非垞に類䌌した結果であり、䜿甚される機胜の数は非垞に少ない。

たあ、それは私が望むすべおです。

ここに「Zhoposranchik」氏ずの別れの写真がありたす。それが誰かを怒らせたり、「holivarov」を匕き起こさないこずを願っおいたす:)

Source: https://habr.com/ru/post/J340698/


All Articles