1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
| import elasticsearch import elasticsearch.helpers import re import numpy as np import operator import datetime
es_client = elasticsearch.Elasticsearch(hosts=["localhost:9200"])
def trim_song_name(song_name): """ 处理歌名,过滤掉无用内容和空白 """ song_name = song_name.strip() song_name = re.sub("【.*?】", "", song_name) song_name = re.sub("(.*?)", "", song_name) return song_name
def trim_address_name(address_name): """ 处理地址 """ return str(address_name).strip()
def get_data(size=0): """ 获取uid=>作品名list的字典 """ cur_size=0 song_dic = {} user_address_dic = {} user_decades_dic = {} search_result = elasticsearch.helpers.scan( es_client, index="ktv_user_info", doc_type="ktv_works", scroll="10m", query={ "query":{ "range": { "birthday": { "gt": 63072662400 } )
for hit_item in search_result: cur_size += 1 if size>0 and cur_size>size: break user_info = hit_item["_source"] item = get_work_info(hit_item["_id"]) if item is None: continue
work_list = item['item_list'] if len(work_list)<2: if user_info['gender']==0: if user_info['gender']==1: user_info['gender']="男" if user_info['gender']==2: user_info['gender']="女" song_dic[item['uid']] = [trim_song_name(item['songname']) for item in work_list]
user_decades_dic[item['uid']] = user_info['gender'] user_address_dic[item['uid']] = trim_address_name(user_info['address']) return (song_dic, user_address_dic, user_decades_dic)
def get_user_info(uid): """ 获取用户信息 """ ret = es_client.get( id=uid ) return ret['_source']
def get_work_info(uid): """ """ try: index="ktv_works", ) except Exception as ex: return None
def get_uniq_song_sort_list(song_dict): """ 合并重复歌曲并按歌曲名排序 """ return sorted(list(set(np.concatenate(list(song_dict.values())).tolist()))) from sklearn import preprocessing %run label_encoder.ipynb
user_count = 4000 song_count = 0
# 获得用户唱歌数据 song_dict, user_address_dict, user_decades_dict = get_data(user_count)
# 歌曲字典 song_label_encoder = LabelEncoder() song_label_encoder.fit_dict(song_dict, "", True) song_hot_matrix = song_label_encoder.encode_hot_dict(song_dict, True)
user_decades_encoder = LabelEncoder() user_decades_encoder.fit_dict(user_decades_dict) decades_hot_matrix = user_decades_encoder.encode_hot_dict(user_decades_dict, False)
``` ##### song_hot_matrix uid 洗刷刷 麻雀 你的答案 0
0
1
0 1
1
1
0 2
1
0
0 3
0
0
0 ##### decades_hot_matrix uid 男 女 0
1
0 1
0
1 2
1
0 3
0
1 ##### 模型训练 ```sql from keras.models import Sequential from keras.layers import Dense, Activation, Embedding,Flatten import matplotlib.pyplot as plt from keras.utils import np_utils from sklearn import datasets from sklearn.model_selection import train_test_split
n_class=user_decades_encoder.get_class_count() song_count=song_label_encoder.get_class_count() print(n_class) print(song_count)
# 拆分训练数据和测试数据 train_X,test_X, train_y, test_y = train_test_split(song_hot_matrix, decades_hot_matrix, test_size = 0.2, random_state = 0) train_count = np.shape(train_X)[0] # 构建神经网络模型 model = Sequential() model.add(Dense(input_dim=8, units=n_class)) model.add(Activation('softmax'))
# 选定loss函数和优化器 model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
# 训练过程 print('Training -----------') for step in range(train_count): scores = model.train_on_batch(train_X, train_y) if step % 50 == 0: print("训练样本 %d 个, 损失: %f, 准确率: %f" % (step, scores[0], scores[1]*100)) print('finish!')
``` ##### 准确率测试集评估 数据训练完了用拆分出来的20%数据测试一下: # 准确率评估 ```java from sklearn.metrics import classification_report scores = model.evaluate(test_X, test_y, verbose=0) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) Y_test = np.argmax(test_y, axis=1) y_pred = model.predict_classes(test_X) print(classification_report(Y_test, y_pred))
|