Skip to content

Commit 89d507d

Browse files
Merge pull request #578 from jiangzhonglian/master
更新QQ群和去掉多余的内容
2 parents e6c5394 + 3fdea26 commit 89d507d

15 files changed

Lines changed: 336 additions & 42 deletions

‎README.md‎

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
* 合作or侵权,请联系: `apachecn@163.com`
1616
* **我们不是 Apache 的官方组织/机构/团体,只是 Apache 技术栈(以及 AI)的爱好者!**
17-
* **ApacheCN - 学习机器学习群【915394271】<a target="_blank" href="//shang.qq.com/wpa/qunwpa?idkey=1577295fb6928b869facd55df9be529464a048389cbe1cea3a133b7708d5ded4"><img border="0" src="http://data.apachecn.org/img/logo/ApacheCN-group.png" alt="ApacheCN - 学习机器学习群[915394271]" title="ApacheCN - 学习机器学习群[915394271]"></a>**
17+
* **ApacheCN - 学习群【724187166】<a target="_blank" href="//shang.qq.com/wpa/qunwpa?idkey=51040bbd0bf7d0efbfa7256a0331d912a2055a906c324d52b02371d06f3c9878"><img border="0" src="http://data.apachecn.org/img/logo/ApacheCN-group.png" alt="ApacheCN - 学习机器学习群[724187166]" title="ApacheCN - 学习机器学习群[724187166]"></a>**
1818

1919
> **欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远**
2020
@@ -489,7 +489,6 @@ mage字幕是为给定图像生成文本描述的任务。
489489
* [@片刻](https://github.com/jiangzhonglian)
490490
* [@那伊抹微笑](https://github.com/wangyangting)
491491
* [@瑶妹](https://github.com/chenyyx)
492-
* [2017-04-08_第一期的总结](/report/2017-04-08_第一期的总结.md)
493492

494493
> Ml 第二期 (2017-08-14)
495494
@@ -500,6 +499,8 @@ mage字幕是为给定图像生成文本描述的任务。
500499

501500
> Ml 第三期 (2018-04-16)
502501
502+
503+
503504
## 项目贡献者
504505

505506
> Ml 第一期 (2017-02-27)
@@ -631,18 +632,3 @@ mage字幕是为给定图像生成文本描述的任务。
631632
## 赞助我们
632633

633634
<img src="http://data.apachecn.org/img/about/donate.jpg" alt="微信&支付宝" />
634-
635-
---
636-
637-
> 特别赞助商(欢迎“私聊”赞助)
638-
639-
<table>
640-
<tbody>
641-
<tr>
642-
<td align="center" valign="middle">
643-
<a href="https://coding.net/?utm_source=ApacheCN&utm_medium=banner&utm_campaign=march2019">
644-
<img width="1080" src="http://data.apachecn.org/img/SpecialSponsors/CodingNet.png">
645-
</a>
646-
</td>
647-
</tbody>
648-
</table>

‎SUMMARY.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@
1616
+ [第15章_大数据与MapReduce](docs/ml/15.大数据与MapReduce.md)
1717
+ [第16章_推荐系统](docs/ml/16.推荐系统.md)
1818
+ [为何录制教学版视频](docs/why-to-record-study-ml-video.md)
19-
+ [加入我们](docs/join-us.md)
19+
+ [2017-04-08_第一期的总结](/report/2017-04-08_第一期的总结.md)

‎docs/join-us.md‎

Lines changed: 0 additions & 21 deletions
This file was deleted.

‎docs/ml/3.决策树.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def classify(inputTree, featLabels, testVec):
318318
classLabel 分类的结果值,需要映射label才能知道名称
319319
"""
320320
# 获取tree的根节点对于的key值
321-
firstStr = inputTree.keys()[0]
321+
firstStr = list(inputTree.keys())[0]
322322
# 通过key得到根节点对应的value
323323
secondDict = inputTree[firstStr]
324324
# 判断根节点名称获取根节点在label中的先后顺序,这样就知道输入的testVec怎么开始对照树来做分类

‎docs/why-to-record-study-ml-video.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,6 @@
133133

134134
## 加入方式
135135

136-
* 机器学习企鹅群: 915394271(MachineLearning)
136+
* 机器学习企鹅群: 724187166(MachineLearning)
137137

138138
ps: 又特喵的收获了一些图片 。。。

‎faq/1.机器学习实战-复习版.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474

7575
## 6.机器学习QQ群
7676

77-
* ApacheCN - 学习机器学习群【915394271】
77+
* ApacheCN - 学习机器学习群【724187166】
7878

7979
***
8080

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import pickle
2+
import numpy as np
3+
import platform
4+
from collections import Counter
5+
6+
from keras.models import Sequential
7+
from keras.layers import Embedding, Bidirectional, LSTM
8+
from keras_contrib.layers import CRF
9+
from keras.preprocessing.sequence import pad_sequences
10+
11+
EMBED_DIM = 200
12+
BiRNN_UNITS = 200
13+
14+
15+
16+
def load_data():
17+
train = _parse_data(open('zh-NER/data/train_data.data', 'rb'))
18+
test = _parse_data(open('zh-NER/data/test_data.data', 'rb'))
19+
20+
word_counts = Counter(row[0].lower() for sample in train for row in sample)
21+
vocab = [w for w, f in iter(word_counts.items()) if f >= 2]
22+
chunk_tags = ['O', 'B-PER', 'I-PER', 'B-LOC', 'I-LOC', "B-ORG", "I-ORG"]
23+
24+
# save initial config data
25+
with open('zh-NER/model/config.pkl', 'wb') as outp:
26+
pickle.dump((vocab, chunk_tags), outp)
27+
28+
train = _process_data(train, vocab, chunk_tags)
29+
test = _process_data(test, vocab, chunk_tags)
30+
return train, test, (vocab, chunk_tags)
31+
32+
33+
def _parse_data(fh):
34+
# in windows the new line is '\r\n\r\n' the space is '\r\n' . so if you use windows system,
35+
# you have to use recorsponding instructions
36+
37+
if platform.system() == 'Windows':
38+
split_text = '\r\n'
39+
else:
40+
split_text = '\n'
41+
42+
string = fh.read().decode('utf-8')
43+
data = [[row.split() for row in sample.split(split_text)] for
44+
sample in
45+
string.strip().split(split_text + split_text)]
46+
fh.close()
47+
return data
48+
49+
50+
def _process_data(data, vocab, chunk_tags, maxlen=None, onehot=False):
51+
if maxlen is None:
52+
maxlen = max(len(s) for s in data)
53+
word2idx = dict((w, i) for i, w in enumerate(vocab))
54+
x = [[word2idx.get(w[0].lower(), 1) for w in s] for s in data] # set to <unk> (index 1) if not in vocab
55+
56+
y_chunk = [[chunk_tags.index(w[1]) for w in s] for s in data]
57+
58+
x = pad_sequences(x, maxlen) # left padding
59+
60+
y_chunk = pad_sequences(y_chunk, maxlen, value=-1)
61+
62+
if onehot:
63+
y_chunk = np.eye(len(chunk_tags), dtype='float32')[y_chunk]
64+
else:
65+
y_chunk = np.expand_dims(y_chunk, 2)
66+
return x, y_chunk
67+
68+
69+
def process_data(data, vocab, maxlen=100):
70+
word2idx = dict((w, i) for i, w in enumerate(vocab))
71+
x = [word2idx.get(w[0].lower(), 1) for w in data]
72+
length = len(x)
73+
x = pad_sequences([x], maxlen) # left padding
74+
return x, length
75+
76+
77+
def create_model(train=True):
78+
if train:
79+
(train_x, train_y), (test_x, test_y), (vocab, chunk_tags) = load_data()
80+
else:
81+
with open('model/config.pkl', 'rb') as inp:
82+
(vocab, chunk_tags) = pickle.load(inp)
83+
model = Sequential()
84+
model.add(Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
85+
model.add(Bidirectional(LSTM(BiRNN_UNITS // 2, return_sequences=True)))
86+
crf = CRF(len(chunk_tags), sparse_target=True)
87+
model.add(crf)
88+
model.summary()
89+
model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
90+
if train:
91+
return model, (train_x, train_y), (test_x, test_y)
92+
else:
93+
return model, (vocab, chunk_tags)
94+
95+
96+
def train():
97+
EPOCHS = 10
98+
model, (train_x, train_y), (test_x, test_y) = create_model()
99+
# train model
100+
model.fit(train_x, train_y,batch_size=16,epochs=EPOCHS, validation_data=[test_x, test_y])
101+
model.save('model/crf.h5')
102+
103+
def test():
104+
model, (vocab, chunk_tags) = create_model(train=False)
105+
predict_text = '中华人民共和国国务院总理周恩来在外交部长陈毅的陪同下,连续访问了埃塞俄比亚等非洲10国以及阿尔巴尼亚'
106+
str, length = process_data(predict_text, vocab)
107+
model.load_weights('model/crf.h5')
108+
raw = model.predict(str)[0][-length:]
109+
result = [np.argmax(row) for row in raw]
110+
result_tags = [chunk_tags[i] for i in result]
111+
112+
per, loc, org = '', '', ''
113+
114+
for s, t in zip(predict_text, result_tags):
115+
if t in ('B-PER', 'I-PER'):
116+
per += ' ' + s if (t == 'B-PER') else s
117+
if t in ('B-ORG', 'I-ORG'):
118+
org += ' ' + s if (t == 'B-ORG') else s
119+
if t in ('B-LOC', 'I-LOC'):
120+
loc += ' ' + s if (t == 'B-LOC') else s
121+
122+
print(['person:' + per, 'location:' + loc, 'organzation:' + org])
123+
124+
125+
if __name__ == "__main__":
126+
train()
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
5+
# C extensions
6+
*.so
7+
8+
# Distribution / packaging
9+
.Python
10+
env/
11+
build/
12+
develop-eggs/
13+
dist/
14+
eggs/
15+
lib/
16+
lib64/
17+
parts/
18+
sdist/
19+
var/
20+
*.egg-info/
21+
.installed.cfg
22+
*.egg
23+
24+
# Installer logs
25+
pip-log.txt
26+
pip-delete-this-directory.txt
27+
28+
# Unit test / coverage reports
29+
htmlcov/
30+
.tox/
31+
.coverage
32+
.cache
33+
nosetests.xml
34+
coverage.xml
35+
36+
# Translations
37+
*.mo
38+
*.pot
39+
40+
# Django stuff:
41+
*.log
42+
43+
# Sphinx documentation
44+
docs/_build/
45+
.idea
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# zh-NER-keras
2+
> this project is a sample for Chinese Named Entity Recognition(NER)
3+
by Keras 2.1.4
4+
5+
## requirements
6+
* keras=>2.1.4
7+
* keras contribute 2.0.8 (https://github.com/keras-team/keras-contrib)
8+
* h5py
9+
* pickle
10+
11+
## demo
12+
13+
```python
14+
15+
python val.py
16+
17+
```
18+
19+
20+
input:
21+
```text
22+
中华人民共和国国务院总理周恩来在外交部长陈毅,
23+
副部长王东的陪同下,
24+
连续访问了埃塞俄比亚等非洲10国以及阿尔巴尼亚
25+
```
26+
output:
27+
```python
28+
['person: 周恩来 陈毅, 王东', 'location: 埃塞俄比亚 非洲 阿尔巴尼亚', 'organzation: 中华人民共和国国务院 外交部']
29+
30+
```
31+
32+
33+
34+
35+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from keras.models import Sequential
2+
from keras.layers import Embedding, Bidirectional, LSTM
3+
from keras_contrib.layers import CRF
4+
import process_data
5+
import pickle
6+
7+
EMBED_DIM = 200
8+
BiRNN_UNITS = 200
9+
10+
11+
def create_model(train=True):
12+
if train:
13+
(train_x, train_y), (test_x, test_y), (vocab, chunk_tags) = process_data.load_data()
14+
else:
15+
with open('model/config.pkl', 'rb') as inp:
16+
(vocab, chunk_tags) = pickle.load(inp)
17+
model = Sequential()
18+
model.add(Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
19+
model.add(Bidirectional(LSTM(BiRNN_UNITS // 2, return_sequences=True)))
20+
crf = CRF(len(chunk_tags), sparse_target=True)
21+
model.add(crf)
22+
model.summary()
23+
model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
24+
if train:
25+
return model, (train_x, train_y), (test_x, test_y)
26+
else:
27+
return model, (vocab, chunk_tags)

0 commit comments

Comments
 (0)