Skip to content

Commit 91da359

Browse files
committed
ENH Update to Python 3. Better figures
1 parent 7fd23a3 commit 91da359

File tree

2 files changed

+16
-20
lines changed

2 files changed

+16
-20
lines changed

ch04/blei_lda.py

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,6 @@
1515
print("Please install it")
1616
raise
1717

18-
try:
19-
from mpltools import style
20-
style.use('ggplot')
21-
except:
22-
print("Could not import mpltools: plots will not be styled correctly")
23-
2418
import matplotlib.pyplot as plt
2519
import numpy as np
2620
from os import path
@@ -39,9 +33,8 @@
3933
model = models.ldamodel.LdaModel(
4034
corpus, num_topics=NUM_TOPICS, id2word=corpus.id2word, alpha=None)
4135

42-
ti = 0
4336
# Iterate over all the topics in the model
44-
for ti in xrange(model.num_topics):
37+
for ti in range(model.num_topics):
4538
words = model.show_topic(ti, 64)
4639
tf = sum(f for f, w in words)
4740
with open('topics.txt', 'w') as output:
@@ -68,11 +61,12 @@
6861
create_cloud('cloud_blei_lda.png', words)
6962

7063
num_topics_used = [len(model[doc]) for doc in corpus]
71-
plt.hist(num_topics_used, np.arange(42))
72-
plt.ylabel('Nr of documents')
73-
plt.xlabel('Nr of topics')
74-
plt.savefig('Figure_04_01.png')
75-
plt.clf()
64+
fig,ax = plt.subplots()
65+
ax.hist(num_topics_used, np.arange(42))
66+
ax.set_ylabel('Nr of documents')
67+
ax.set_xlabel('Nr of topics')
68+
fig.tight_layout()
69+
fig.savefig('Figure_04_01.png')
7670

7771

7872
# Now, repeat the same exercise using alpha=1.0
@@ -83,12 +77,14 @@
8377
corpus, num_topics=NUM_TOPICS, id2word=corpus.id2word, alpha=ALPHA)
8478
num_topics_used1 = [len(model1[doc]) for doc in corpus]
8579

86-
plt.hist([num_topics_used, num_topics_used1], np.arange(42))
87-
plt.ylabel('Nr of documents')
88-
plt.xlabel('Nr of topics')
80+
fig,ax = plt.subplots()
81+
ax.hist([num_topics_used, num_topics_used1], np.arange(42))
82+
ax.set_ylabel('Nr of documents')
83+
ax.set_xlabel('Nr of topics')
8984

9085
# The coordinates below were fit by trial and error to look good
91-
plt.text(9, 223, r'default alpha')
92-
plt.text(26, 156, 'alpha=1.0')
93-
plt.savefig('Figure_04_02.png')
86+
ax.text(9, 223, r'default alpha')
87+
ax.text(26, 156, 'alpha=1.0')
88+
fig.tight_layout()
89+
fig.savefig('Figure_04_02.png')
9490

ch04/build_lda.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __len__(self):
7979

8080
distances = distance.squareform(distance.pdist(thetas))
8181
large = distances.max() + 1
82-
for i in xrange(len(distances)):
82+
for i in range(len(distances)):
8383
distances[i, i] = large
8484

8585
print(otexts[1])

0 commit comments

Comments
 (0)