新實戰項目-機器學習-紀錄片播放量預測

介紹一下這個項目其實是一個真實的企業的項目比較新。項目也可以擴展到一些電影的預測,票房預測等等。

新實戰項目-機器學習-紀錄片播放量預測

新實戰項目-機器學習-紀錄片播放量預測

也可以降低一下數據的相關性!

開始

紀錄片播放量預測,迴歸問題 實際項目!!!!!!!!!!!!!!!!

<code># %pip install wordcloud//沒導包的可以這樣下載
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LinearRegression,Ridge
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn import metrics
import jieba
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import TruncatedSVD
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import warnings
warnings.filterwarnings('ignore')
/<code>

一、數據檢索

在此項目中,每部紀錄片的名稱都是獨立的,如果片名參與運算的話,會提升模型複雜度,造成過擬合的情況

<code>data = pd.read_excel('./datas/紀錄片播放量.xls',index_col='片名')//片名不考慮,做標籤了
data.head()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

像不像B站O(∩_∩)O哈哈~

提問:為什麼播放數是object類型? 因為數據上裡面的是1.2萬這種數據!

<code>data.info()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

刪除干擾特徵

<code>del data['標籤']
del data['上傳日期']//應該又會有關係的,但是刪除就刪除了

print('刪除干擾特徵')
/<code>

二、數據挖掘

2.1對上萬條信息進行數據調整 處理Object的數據

<code>def f(s):
'''
如果特徵中統計值出現‘萬’字,將‘萬’字刪除,數字後面添加4個0
args:
s: 原始數據特徵,object類型統計值(部分數據包含‘萬’)
return:
強轉成float類型後的數據
'''
str = '萬'
if str in s:
return float(s[0:-1])*10000 #切片 0:-1 包前不包後
else:
return float(s)
/<code>
<code># 分別對有可能存在‘萬’字的數據進行修改調整
col = ['播放數','彈幕數','收藏數']
for i in col:
# 使用map方法將上述所表示的三列數據進行數值調整
data[i] = data[i].map(f)
print(data.info())
/<code>
新實戰項目-機器學習-紀錄片播放量預測

可以看出,播放數量明顯屬於連續型數值

<code>data['播放數'].value_counts()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

可以發現數據之間的差距還是非常大的

<code>data['播放數'].map(lambda x: float(x))
data['播放數'].plot('kde')
plt.show()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

<code>data.describe() 
/<code>
新實戰項目-機器學習-紀錄片播放量預測

2.2對簡介信息進行數據挖掘

中文分詞操作

<code>#使用精確分詞模式,將特徵中的信息進行中文分詞,簡介中的信息是一個列表
data['簡介'] = data['簡介'].map(lambda x:jieba.lcut(x))
# 返回的是一個列表, 後續使用特徵詞進行處理,認為一個字的分詞形式對於後續處理模型沒有作用,刪除掉
data['簡介'] = data['簡介'].map(lambda x:[i for i in x if len(i) > 1])
data['簡介'].head()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

停用詞處理: 在jieba處理後的詞語,有一些是對模型不適用的詞語,所以要進行去除,利用之前做好的停用詞表進行處理

<code># 分隔符\\n\\t 以及常見單詞
stop = pd.read_csv('./datas/stopwords.txt',sep='\\n\\t',engine='python',encoding='utf-8')
stop.head()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

去除特徵中的停用詞 將數據轉化為可以使用詞頻統計的方式

<code># 如果特徵中的單詞不屬於停用詞,進行保留,否則去除
data['簡介'] = data['簡介'].map(lambda x:[i for i in x if i not in stop])
# 將處理後的特徵拼接成一個字符串,每個單詞之間使用空格連接
data['簡介'] = data['簡介'].map(lambda x:' '.join(i for i in x))
data['簡介'].head()
/<code>

加空格是為了配合TF-IDF的英文特點

新實戰項目-機器學習-紀錄片播放量預測

<code># 將所有樣本單詞轉化成一個列表
list_data = data['簡介'].tolist() # 首先轉化為一個列表 變成list結構 每個元素是一句話

list_data
/<code>
新實戰項目-機器學習-紀錄片播放量預測

<code>wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(list_data[1])
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
/<code>
新實戰項目-機器學習-紀錄片播放量預測

三、數據預處理

詞頻處理

<code>x1 = CountVectorizer().fit_transform(list_data)
x1.shape
/<code>
<code>(1186, 12893)//(數據量,特徵)
/<code>

詞頻中特徵過多,複雜度較高進行降維處理

<code>pc = TruncatedSVD(n_components=10)   # 設置降為10個維度
x1 = pc.fit_transform(x1)
x1
/<code>
新實戰項目-機器學習-紀錄片播放量預測

去除簡介列

<code>del data['簡介']
print('去除簡介列')
/<code>

四、模型創建及評估

提取特徵和標籤

<code># 標籤
target = ['播放數']
# 特徵
feature = [x for x in data.columns if x not in target]
/<code>

對標籤值進行對數處理,原因詳見PPT

<code>data[target] = np.log(data[target])
/<code>
<code># 數據進行標準化處理
# 一次性切片多列
data[feature] = StandardScaler().fit_transform(data[feature])
/<code>

對特徵和標籤進行切片處理

<code>y = data.loc[:,target]
x2 = data.loc[:,feature].as_matrix()
print(x2.shape)
# 合併數據 x1就是簡介後的數據 (向量化)
x = np.concatenate((x1,x2),axis=1)
print(x.shape)
/<code>
<code>(1186, 7)
(1186, 17)//17個特徵
/<code>
<code># 劃分數據集
trainx,testx,trainy,testy = train_test_split(x,y,test_size=0.3,random_state=123)
print(trainx.shape)
print(testx.shape)
/<code>
<code>(830, 17)
(356, 17)
/<code>

線性模型預測效果

<code>l2 = Ridge()
param_grid = {'alpha': [0.1, 1, 10, 100, 1000, 10000]}
model = GridSearchCV(l2, param_grid=param_grid, cv=10)
model.fit(trainx, trainy)
print(model.best_params_)
print(model.score(testx, testy))
/<code>

這個LR線性迴歸模型,效果就很辣雞了!!

<code>{'alpha': 1000}
0.3317827436601407
/<code>

隨機森林模型預測效果

<code>rf = RandomForestRegressor()

param_grid = {

'n_estimators': [10, 100, 100, 500],
'max_depth': [2, 3, 4, 5, 6, 7]
}
model = GridSearchCV(rf, param_grid=param_grid, cv=10)//網格搜索交叉驗證
model.fit(trainx, trainy)
print(model.best_params_)
print(model.score(testx, testy))
/<code>
<code>{'max_depth': 7, 'n_estimators': 500}
0.8476172334620827
/<code>

GBDT模型預測效果

<code>gbdt = GradientBoostingRegressor()

param_grid = {

'n_estimators': [10, 100, 100, 500, 1000],
'max_depth': [2, 3, 4, 5]
}
model = GridSearchCV(gbdt, param_grid=param_grid, cv=10)
model.fit(trainx, trainy)
print(model.best_params_)
print(model.score(testx, testy))
/<code>
<code>{'max_depth': 5, 'n_estimators': 1000}
0.8522771940332649
/<code>

注意上面的模型的調參,舉個例子,最大深度設置是5,實際也是5,那得放大設計的參數!

隨機森林和GBDT你選哪個? 當然是隨機森林啦,在實際的項目部署中隨機森林可以分佈式部署,多棵樹的擴容改造!!

私聊我給你發代碼!!!!


分享到:


相關文章: