Demo entry 6359818

BuildModelForElectronicsData

   

Submitted by anonymous on Apr 29, 2017 at 21:35
Language: Python. Code size: 3.9 kB.

from scipy.signal import square, sawtooth
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from keras.utils import np_utils 
from keras.models import Sequential 
from keras.models import model_from_json 
from keras.layers import Dense, Activation, Dropout 
from sklearn.cross_validation import train_test_split 
from tqdm import tqdm
import time
N = 1000

def one_hot_encode_object_array(arr): 
    uniques, ids = np.unique(arr, return_inverse=True) 
    return np_utils.to_categorical(ids, len(uniques)) 

def pick_signal(options):
    return np.random.randint(0, options)

def build_model(af='relu', classes=2):
	model = Sequential()
	model.add(Dense(1000, input_dim=500))
	model.add(Activation(af))
	model.add(Dropout(0.2))
	model.add(Dense(300))
	model.add(Activation(af))
	model.add(Dropout(0.5))
	model.add(Dense(classes))
	model.add(Activation('softmax'))

	model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

	return model

def save_model(model, name='ModelOne'): 
    model_json = model.to_json() 
    with open(f'{name}.json', 'w') as f: 
        f.write(model_json) 
    model.save_weights(f'{name}.h5') 
    print('Saved Model to Disk') 

def build_data(M=5000):

	dt = 1/1000

	frequency = np.random.uniform(1, 1000, M)
	frequency = [1.76] * M
	noise_range = [0, 5]
	noise = np.random.uniform(noise_range[0], noise_range[1], M)
	duty_range = [0.01, 0.5]
	duty = np.random.uniform(duty_range[0], duty_range[1], M)
	x_data = list()
	y_data = list()
	c_data = list()
	pfrac = 0.5
	for c in tqdm(range(M)):
		signal = pick_signal(options=4)
		t = np.linspace(0, N*dt, N)
		if signal == 1:
			y = square(2*np.pi*frequency[c]*t, duty[c])
			y += np.random.normal(0, noise[c], N)
		elif signal == 0:
			y = np.random.normal(0, noise[c], N)
		elif signal == 2:
			y = sawtooth(2 * np.pi * frequency[c] * t, 0.5)
			y += np.random.normal(0, noise[c], N)
		elif signal == 3:
			y = np.sin(2 * np.pi * frequency[c] * t)
			y += np.random.normal(0, noise[c], N)
		yf = fft(y)
		tf = np.linspace(.0, 1./(2.*dt), N/2)
		spectrum = 2./N * np.abs(yf[0:N//2])
		x_data.append(tf)
		y_data.append(spectrum)
		c_data.append(int(signal))
		# plt.title("Signal Present: {}, Duty Cycle: {}".format(signal, duty[c]))
		# plt.plot(tf, spectrum)
		# plt.show()
	return np.array(y_data).reshape(int(M), int(N/2)), np.array(c_data)

def main():
	model = build_model(classes=4)
	X, C = build_data(M=100000)
	print(C.shape)
	X_train, X_test, Y_train, Y_test = train_test_split(X, C, test_size=0.33, random_state=42)
	# X_train = X_train.reshape(int(N/2), len(X_train))
	print(X_train.shape)
	Y_train_ohe = one_hot_encode_object_array(Y_train)
	Y_test_ohe = one_hot_encode_object_array(Y_test)
	model.fit(X_train, Y_train_ohe, verbose=1, nb_epoch=25, batch_size=100)
	score = model.evaluate(X_test, Y_test_ohe, verbose=0)
	print('The Model preforms: {}'.format(score)) 
	predictions = model.predict_classes(X_test, verbose=0)
	predictions = predictions.tolist()
	for i, e in enumerate(predictions):
		if e == 0:
			predictions[i] = [0, 0, 0]
		elif e == 1:
			predictions[i] = [1, 0, 0]
		elif e == 2:
			predictions[i] = [1, 1, 0]
		elif e == 3:
			predictions[i] = [0, 1, 1]
	mn = list()
	mp = list()
	save_model(model, name='4Class')
	for e in X_test:
		mp.append(max(e))
		mn.append(np.median(e))
	plt.scatter(mp, mn, c=predictions)
	plt.grid()
	plt.title('2000 X 2000 X 2 Model\nClassification of Noisy Square Waves\nAccuracy: {}%, Confidence: {}%'.format(score[1]*100, 100-score[0]*100))
	plt.xlabel('Mean Noise [Non Normalized]')
	plt.ylabel('Max Peak [Non Normalized]')
	plt.savefig('Classify_{}.pdf'.format(time.time()), dpi=350, bbox_inches='tight')
	plt.show()

if __name__=='__main__':
	main()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).