声明:版权所有,转载请联系作者并注明出处 http://blog.csdn.net/u013719780?viewmode=contents
上一个实验机器学习实验(十):基于WiFi fingerprints用自编码器(Autoencoders)和神经网络(Neural Network)进行定位_1(tensorflow版)是用tensorflow实现的,本次用keras实现一下,具体代码如下:
import pandas as pd
import numpy as np
from sklearn.preprocessing import scale
dataset = pd.read_csv("trainingData.csv",header = 0)
features = scale(np.asarray(dataset.ix[:,0:520]))
labels = np.asarray(dataset["BUILDINGID"].map(str) + dataset["FLOOR"].map(str))
labels = np.asarray(pd.get_dummies(labels))
train_val_split = np.random.rand(len(features)) < 0.70
train_x = features[train_val_split]
train_y = labels[train_val_split]
val_x = features[~train_val_split]
val_y = labels[~train_val_split]
test_dataset = pd.read_csv("validationData.csv",header = 0)
test_features = scale(np.asarray(test_dataset.ix[:,0:520]))
test_labels = np.asarray(test_dataset["BUILDINGID"].map(str) + test_dataset["FLOOR"].map(str))
test_labels = np.asarray(pd.get_dummies(test_labels))
from keras.models import Sequential
from keras.layers import Dense
import time
nb_epochs = 20
batch_size = 10
input_size = 520
num_classes = 13
def encoder():
model = Sequential()
model.add(Dense(256, input_dim=input_size, activation='tanh', bias=True))
model.add(Dense(128, activation='tanh', bias=True))
model.add(Dense(64, activation='tanh', bias=True))
return model
def decoder(e):
e.add(Dense(128, input_dim=64, activation='tanh', bias=True))
e.add(Dense(256, activation='tanh', bias=True))
e.add(Dense(input_size, activation='tanh', bias=True))
e.compile(optimizer='adam', loss='mse')
return e
e = encoder()
d = decoder(e)
d.fit(train_x, train_x, nb_epoch=nb_epochs, batch_size=batch_size, verbose=2)
time.sleep(0.1)
def classifier(d):
num_to_remove = 3
for i in range(num_to_remove):
d.pop()
d.add(Dense(128, input_dim=64, activation='tanh', bias=True))
d.add(Dense(128, activation='tanh', bias=True))
d.add(Dense(num_classes, activation='softmax', bias=True))
d.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])
return d
c = classifier(d)
c.fit(train_x, train_y, validation_data=(val_x, val_y), nb_epoch=nb_epochs, batch_size=batch_size, verbose=2)
time.sleep(0.1)
loss, acc = c.evaluate(test_features, test_labels, verbose=0)
time.sleep(0.1)
print loss, acc