Skip to content

Commit 8de43c3

Browse files
author
whyboris
committed
wip
0 parents  commit 8de43c3

11 files changed

+1972
-0
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
.ipynb_checkpoints
2+
.vscode
3+
__pycache__
4+
output
5+
venv
6+

con-net-mnist.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
print('Convnet solution to MNIST dataset')
2+
3+
from hack import hack
4+
5+
hack()
6+
7+
from keras import datasets
8+
9+
from keras.utils.np_utils import to_categorical
10+
11+
(train_images, train_labels), (validation_images, validation_labels) = datasets.mnist.load_data()
12+
13+
train_images = train_images.reshape((60000, 28, 28, 1))
14+
train_images = train_images.astype('float32') / 255
15+
16+
validation_images = validation_images.reshape((10000, 28, 28, 1))
17+
validation_images = validation_images.astype('float32') / 255
18+
19+
train_labels = to_categorical(train_labels)
20+
validation_labels = to_categorical(validation_labels)
21+
22+
23+
from keras import models
24+
from keras import layers
25+
26+
model = models.Sequential()
27+
28+
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
29+
model.add(layers.MaxPooling2D((2, 2)))
30+
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
31+
model.add(layers.MaxPooling2D((2, 2)))
32+
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
33+
model.add(layers.Flatten())
34+
model.add(layers.Dense(64, activation='relu'))
35+
model.add(layers.Dense(10, activation='softmax'))
36+
37+
model.summary()
38+
39+
model.compile(optimizer='rmsprop',
40+
loss='categorical_crossentropy',
41+
metrics=['accuracy'])
42+
43+
model.fit(train_images, train_labels, epochs=5, batch_size=64)
44+
45+
test_loss, test_accuracy = model.evaluate(validation_images, validation_labels)
46+
47+
print(test_accuracy)
48+
49+
50+
51+
52+
53+

hack.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import os
2+
import ssl
3+
4+
def hack():
5+
6+
# --------------------------------------------------------------------
7+
# disable the error:
8+
# `Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA`
9+
# --------------------------------------------------------------------
10+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
11+
12+
# --------------------------------------------------------------------
13+
# hack to avoid SSL download error
14+
# --------------------------------------------------------------------
15+
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
16+
getattr(ssl, '_create_unverified_context', None)):
17+
ssl._create_default_https_context = ssl._create_unverified_context
18+
19+

imdb.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
print('IMDB classification')
2+
3+
from hack import hack
4+
5+
hack()
6+
7+
8+
import keras
9+
print('keras version ' + keras.__version__)
10+
11+
import numpy as np
12+
13+
def vectorize_sequences(sequences, dimension=10000):
14+
results = np.zeros((len(sequences), dimension))
15+
for i, sequence in enumerate(sequences):
16+
results[i, sequence] = 1.
17+
return results
18+
19+
20+
21+
from keras.datasets import imdb
22+
23+
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
24+
25+
# print(train_data[0])
26+
27+
x_train = vectorize_sequences(train_data)
28+
x_test = vectorize_sequences(test_data)
29+
30+
# print(x_train[0])
31+
32+
y_train = np.asarray(train_labels).astype('float32')
33+
y_test = np.asarray(test_labels).astype('float32')
34+
35+
36+
from keras import layers
37+
from keras import models
38+
# from keras import optimizers
39+
40+
model = models.Sequential()
41+
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
42+
model.add(layers.Dense(16, activation='relu'))
43+
model.add(layers.Dense(1, activation='sigmoid'))
44+
45+
model.compile(optimizer='rmsprop',
46+
loss='binary_crossentropy',
47+
metrics=['accuracy'])
48+
49+
x_val = x_train[:10000]
50+
partial_x_train = x_train[10000:]
51+
52+
y_val = y_train[:10000]
53+
partial_y_train = y_train[10000:]
54+
55+
history = model.fit(partial_x_train,
56+
partial_y_train,
57+
epochs=4,
58+
batch_size=512,
59+
validation_data=(x_val, y_val))
60+
61+
62+
history_dict = history.history
63+
print(history_dict.keys())
64+
65+
import matplotlib.pyplot as plt
66+
67+
acc = history.history['acc']
68+
loss_values = history_dict['loss']
69+
val_loss_values = history_dict['val_loss']
70+
71+
epochs = range(1, len(acc) + 1)
72+
73+
plt.plot(epochs, loss_values, 'bo', label='Training loss')
74+
plt.plot(epochs, val_loss_values, 'b', label='Validation loss')
75+
plt.title('Training and validation loss')
76+
plt.xlabel('Epochs')
77+
plt.ylabel('Loss')
78+
plt.legend()
79+
80+
plt.show()
81+
82+
# print(model.predict(x_test))
83+

news.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
print('Newswire classification')
2+
3+
from hack import hack
4+
5+
hack()
6+
7+
8+
from keras.datasets import reuters
9+
10+
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
11+
12+
print('train data: ' + str(len(train_data)))
13+
print('test data: ' + str(len(test_data)))
14+
15+
print(train_data[10])
16+
17+
# -- if you want to see inside the train_data, here's an example:
18+
# word_index = reuters.get_word_index()
19+
# reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
20+
# decoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])
21+
# print(decoded_newswire)
22+
23+
import numpy as np
24+
25+
def vectorize_sequences(sequences, dimension=10000):
26+
results = np.zeros((len(sequences), dimension))
27+
for i, sequence in enumerate(sequences):
28+
results[i, sequence] = 1.
29+
return results
30+
31+
x_train = vectorize_sequences(train_data)
32+
x_test = vectorize_sequences(test_data)
33+
34+
# create a one-hot (categorical) encoding
35+
def to_one_hot(labels, dimension=46):
36+
results = np.zeros((len(labels), dimension))
37+
for i, label in enumerate(labels):
38+
results[i, label] = 1.
39+
return results
40+
41+
one_hot_train_lables = to_one_hot(train_labels)
42+
one_hot_test_labels = to_one_hot(test_labels)
43+
44+
45+
# or more-simply use the pre-built keras method
46+
from keras.utils.np_utils import to_categorical
47+
48+
one_hot_train_labels = to_categorical(train_labels)
49+
one_hot_test_labels = to_categorical(test_labels)
50+
51+
52+
from keras import models
53+
from keras import layers
54+
55+
model = models.Sequential()
56+
57+
model.add(layers.Dense(46, activation='relu', input_shape=(10000,)))
58+
model.add(layers.Dense(46, activation='relu'))
59+
model.add(layers.Dense(46, activation='softmax'))
60+
61+
model.compile(optimizer='rmsprop',
62+
loss='categorical_crossentropy',
63+
metrics=['accuracy'])
64+
65+
x_val = x_train[:1000]
66+
partial_x_train = x_train[1000:]
67+
68+
y_val = one_hot_train_labels[:1000]
69+
partial_y_train = one_hot_train_labels[1000:]
70+
71+
history = model.fit(partial_x_train,
72+
partial_y_train,
73+
epochs=20,
74+
batch_size=516,
75+
validation_data=(x_val, y_val))
76+
77+
import matplotlib.pyplot as plt # pylint disable=E0401
78+
79+
loss = history.history['loss']
80+
val_loss = history.history['val_loss']
81+
82+
epochs = range(1, len(loss) + 1)
83+
84+
plt.plot(epochs, loss, 'bo', label='Training loss')
85+
plt.plot(epochs, val_loss, 'b', label='Validation loss')
86+
plt.title('Training and validation loss')
87+
plt.xlabel('Epochs')
88+
plt.ylabel('Loss')
89+
plt.legend()
90+
91+
plt.show()
92+
93+
plt.clf()
94+
95+
accuracy = history.history['acc']
96+
val_acc = history.history['val_acc']
97+
98+
plt.plot(epochs, accuracy, 'bo', label='Accuracy')
99+
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
100+
plt.title('Training and validation accuracy')
101+
plt.xlabel('Epochs')
102+
plt.ylabel('Accuracy')
103+
plt.legend()
104+
105+
plt.show()
106+
107+
108+
109+
110+
111+
112+
113+

0 commit comments

Comments
 (0)