Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 160bee7

Browse files
committed
Class updates and extras
1 parent 35c2ed6 commit 160bee7

File tree

8 files changed

+64
-55
lines changed

8 files changed

+64
-55
lines changed

keras-audio/gru-composer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ class Midi(Callback):
135135
Callback for sampling a midi file
136136
"""
137137

138-
def sample(self, preds, temperature=1.0):
138+
def sample(self, preds, temperature=1):
139139
# helper function to sample an index from a probability array
140140
preds = np.asarray(preds).astype('float64')
141141
preds = np.log(preds) / temperature
@@ -163,7 +163,7 @@ def generate_notes(self, network_input, pitchnames, n_vocab):
163163

164164
prediction = model.predict(prediction_input, verbose=0)
165165

166-
index = self.sample(prediction[0], temperature=0.5)#np.argmax
166+
index = self.sample(prediction[0], temperature=0.5) # np.argmax
167167
result = int_to_note[index]
168168
prediction_output.append(result)
169169

keras-autoencoder/variational_autoencoder.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
# reparameterization trick
1818
# instead of sampling from Q(z|X), sample eps = N(0,I)
1919
# z = z_mean + sqrt(var)*eps
20+
21+
2022
def sampling(args):
2123
"""Reparameterization trick by sampling fr an isotropic unit Gaussian.
2224
# Arguments:
@@ -32,6 +34,7 @@ def sampling(args):
3234
epsilon = K.random_normal(shape=(batch, dim))
3335
return z_mean + K.exp(0.5 * z_log_var) * epsilon
3436

37+
3538
# MNIST dataset
3639
(x_train, y_train), (x_test, y_test) = mnist.load_data()
3740

@@ -78,7 +81,7 @@ def sampling(args):
7881
data = (x_test, y_test)
7982

8083
reconstruction_loss = binary_crossentropy(inputs,
81-
outputs)
84+
outputs)
8285

8386
reconstruction_loss *= original_dim
8487
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
@@ -88,10 +91,10 @@ def sampling(args):
8891
vae.add_loss(vae_loss)
8992
vae.compile(optimizer='adam')
9093

94+
9195
vae.fit(x_train,
92-
epochs=epochs,
93-
batch_size=batch_size,
94-
validation_data=(x_test, None),
95-
callbacks=[WandbCallback(), PlotCallback(encoder, decoder, (x_test, y_test))] )
96+
epochs=epochs,
97+
batch_size=batch_size,
98+
validation_data=(x_test, None),
99+
callbacks=[WandbCallback(), PlotCallback(encoder, decoder, (x_test, y_test))])
96100
vae.save_weights('vae_mlp_mnist.h5')
97-

keras-cnn/cnn.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from keras.utils import np_utils
55
from wandb.keras import WandbCallback
66
import wandb
7+
import os
78

89
run = wandb.init()
910
config = run.config
@@ -23,31 +24,33 @@
2324
X_test = X_test.astype('float32')
2425
X_test /= 255.
2526

26-
#reshape input data
27-
X_train = X_train.reshape(X_train.shape[0], config.img_width, config.img_height, 1)
28-
X_test = X_test.reshape(X_test.shape[0], config.img_width, config.img_height, 1)
27+
# reshape input data
28+
X_train = X_train.reshape(
29+
X_train.shape[0], config.img_width, config.img_height, 1)
30+
X_test = X_test.reshape(
31+
X_test.shape[0], config.img_width, config.img_height, 1)
2932

3033
# one hot encode outputs
3134
y_train = np_utils.to_categorical(y_train)
3235
y_test = np_utils.to_categorical(y_test)
3336
num_classes = y_test.shape[1]
34-
labels=range(10)
37+
labels = range(10)
3538

3639
# build model
3740
model = Sequential()
3841
model.add(Conv2D(32,
39-
(config.first_layer_conv_width, config.first_layer_conv_height),
40-
input_shape=(28, 28,1),
41-
activation='relu'))
42+
(config.first_layer_conv_width, config.first_layer_conv_height),
43+
input_shape=(28, 28, 1),
44+
activation='relu'))
4245
model.add(MaxPooling2D(pool_size=(2, 2)))
4346
model.add(Flatten())
4447
model.add(Dense(config.dense_layer_size, activation='relu'))
4548
model.add(Dense(num_classes, activation='softmax'))
4649

4750
model.compile(loss='categorical_crossentropy', optimizer='adam',
48-
metrics=['accuracy'])
51+
metrics=['accuracy'])
4952

5053

5154
model.fit(X_train, y_train, validation_data=(X_test, y_test),
52-
epochs=config.epochs,
53-
callbacks=[WandbCallback(data_type="image", save_model=False)])
55+
epochs=config.epochs,
56+
callbacks=[WandbCallback(data_type="image", save_model=False)])

keras-cnn/wandb/settings

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[default]
22
entity: qualcomm
3-
project: digits-feb1
3+
project: digits-mar26
44
base_url: https://api.wandb.ai

keras-mlp/wandb/settings

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[default]
22
entity: qualcomm
3-
project: digits-feb1
3+
project: digits-mar26
44
base_url: https://api.wandb.ai

keras-perceptron/wandb/settings

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[default]
22
entity: qualcomm
3-
project: digits-feb1
3+
project: digits-mar26
44
base_url: https://api.wandb.ai

time-series/plotutil.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,42 @@
11
import matplotlib
22
matplotlib.use('Agg')
3-
import matplotlib.pyplot as plt
4-
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
5-
from matplotlib.figure import Figure
6-
import keras
7-
import numpy as np
83
import wandb
4+
import numpy as np
5+
import keras
6+
from matplotlib.figure import Figure
7+
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
8+
import matplotlib.pyplot as plt
99

10-
def fig2data ( fig ):
10+
11+
def fig2data(fig):
1112
"""
1213
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
1314
@param fig a matplotlib figure
1415
@return a numpy 3D array of RGBA values
1516
"""
1617
# draw the renderer
17-
fig.canvas.draw ( )
18-
18+
fig.canvas.draw()
19+
1920
# Get the RGBA buffer from the figure
20-
w,h = fig.canvas.get_width_height()
21-
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
22-
buf.shape = ( w, h,4 )
23-
21+
w, h = fig.canvas.get_width_height()
22+
buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
23+
buf.shape = (w, h, 4)
24+
2425
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
25-
buf = np.roll ( buf, 3, axis = 2 )
26+
buf = np.roll(buf, 3, axis=2)
2627
return buf
2728

2829

29-
30-
def repeated_predictions(model, data, look_back, steps=100 ):
30+
def repeated_predictions(model, data, look_back, steps=100):
3131
predictions = []
3232
for i in range(steps):
33-
input_data = data[np.newaxis,:,np.newaxis]
33+
input_data = data[np.newaxis, :, np.newaxis]
3434
generated = model.predict(input_data)[0]
3535
data = np.append(data, generated)[-look_back:]
3636
predictions.append(generated)
3737
return predictions
3838

39+
3940
class PlotCallback(keras.callbacks.Callback):
4041
def __init__(self, trainX, trainY, testX, testY, look_back):
4142
self.repeat_predictions = True
@@ -44,22 +45,24 @@ def __init__(self, trainX, trainY, testX, testY, look_back):
4445
self.testX = testX
4546
self.testY = testY
4647
self.look_back = look_back
47-
48+
4849
def on_epoch_end(self, epoch, logs):
4950
if self.repeat_predictions:
50-
preds = repeated_predictions(self.model, self.trainX[-1,:,0], self.look_back, self.testX.shape[0])
51+
preds = repeated_predictions(
52+
self.model, self.trainX[-1, :, 0], self.look_back, self.testX.shape[0])
5153
else:
5254
preds = model.predict(testX)
5355

5456
# Generate a figure with matplotlib</font>
55-
figure = matplotlib.pyplot.figure( figsize=(10,10) )
56-
plot = figure.add_subplot ( 111 )
57+
figure = matplotlib.pyplot.figure(figsize=(10, 10))
58+
plot = figure.add_subplot(111)
5759

58-
plot.plot ( self.trainY )
59-
plot.plot ( np.append(np.empty_like(self.trainY) * np.nan, self.testY))
60-
plot.plot ( np.append(np.empty_like(self.trainY) * np.nan, preds))
60+
plot.plot(self.trainY)
61+
plot.plot(np.append(np.empty_like(self.trainY) * np.nan, self.testY))
62+
plot.plot(np.append(np.empty_like(self.trainY) * np.nan, preds))
6163

62-
data = fig2data ( figure )
64+
data = fig2data(figure)
6365
matplotlib.pyplot.close(figure)
6466

65-
wandb.log({"image": wandb.Image(data)}, commit=False)
67+
if epoch % 4 == 0:
68+
wandb.log({"image": wandb.Image(data)}, commit=False)

time-series/rnn.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
config.repeated_predictions = False
1919
config.look_back = 20
2020

21+
2122
def load_data(data_type="airline"):
2223
if data_type == "flu":
2324
df = pd.read_csv('flusearches.csv')
@@ -31,6 +32,8 @@ def load_data(data_type="airline"):
3132
return data
3233

3334
# convert an array of values into a dataset matrix
35+
36+
3437
def create_dataset(dataset):
3538
dataX, dataY = [], []
3639
for i in range(len(dataset)-config.look_back-1):
@@ -39,12 +42,13 @@ def create_dataset(dataset):
3942
dataY.append(dataset[i + config.look_back])
4043
return np.array(dataX), np.array(dataY)
4144

45+
4246
data = load_data()
43-
47+
4448
# normalize data to between 0 and 1
4549
max_val = max(data)
4650
min_val = min(data)
47-
data=(data-min_val)/(max_val-min_val)
51+
data = (data-min_val)/(max_val-min_val)
4852

4953
# split into train and test sets
5054
split = int(len(data) * 0.70)
@@ -59,11 +63,7 @@ def create_dataset(dataset):
5963

6064
# create and fit the RNN
6165
model = Sequential()
62-
model.add(SimpleRNN(1, input_shape=(config.look_back,1 )))
66+
model.add(SimpleRNN(1, input_shape=(config.look_back, 1)))
6367
model.compile(loss='mse', optimizer='adam')
64-
model.fit(trainX, trainY, epochs=1000, batch_size=1, validation_data=(testX, testY), callbacks=[WandbCallback(), PlotCallback(trainX, trainY, testX, testY, config.look_back)])
65-
66-
67-
68-
69-
68+
model.fit(trainX, trainY, epochs=500, batch_size=1, validation_data=(testX, testY), callbacks=[
69+
WandbCallback(), PlotCallback(trainX, trainY, testX, testY, config.look_back)])

0 commit comments

Comments
 (0)