In [9]:
# import stuff

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

# helper function to issue WAMP remote procedure calls
from wpad import call

In [237]:
# get our sample data for series 12 from Wpadlab object store ..

series_id = 19
series = call("io.crossbar.demo.wpad.objstore.get", "series", series_id)
print("ok, sample of size {} loaded".format(len(series['T'])))


ok, sample of size 13 loaded

In [238]:
# create three scatterplots with raw sensor reading for A4, A5 and A6

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(15, 5)

ax[0].scatter(series['T'], series['A4'], facecolor='r')
ax[1].scatter(series['T'], series['A5'], facecolor='g')
ax[2].scatter(series['T'], series['A6'], facecolor='b')


Out[238]:
<matplotlib.collections.PathCollection at 0x2aacf6167ad0>

In [12]:
# the dataset was created from the Wpad plate which has 3 analog sensors. a number of chocolate bars were
# put on the Wpad plate, starting with 0 bars, then 1, 2, .. up to 15, and then taking away one bar after the other.
# due to the ordering in which weight was applied - gradually increasing, and then decreasing, a sensor
# hysteris effect can be seen.

In [125]:
# next we try to fit a log function to the A4 sensor readings

from scipy.optimize import curve_fit

x = np.array(series['T'])
y = np.array(series['A6'])

# this is the function we try to fit to the data (see above)
def func(x, a, b, c, d):
    return a * np.log(c * x + d) + b

def func(x, a, b):
    return a * x + b
    
popt, pcov = curve_fit(func, x, y)

xn = np.linspace(0,7,500)

plt.plot(x, y, 'ko')
plt.plot(xn, func(xn, *popt), 'r-')

popt


Out[125]:
array([ 11.8255814 ,  62.79069767])

In [248]:
def plot_series(_series):
    models = {}
    
    fig, axs = plt.subplots(1, 3)
    fig.set_size_inches(15, 5)
    
    xn = np.linspace(0, 3.5, 500)
    
    i = 0
    for key in ['A4', 'A5', 'A6']:
        x = np.array(_series['T'])
        y = np.array(_series[key])
    
        axs[i].scatter(x, y)
        axs[i].set_title("Sensor {}".format(key))
        #axs[i].set_xlim([-0.5, 20])
        #axs[i].set_ylim([0, 1023])
        
        if key in []:
            def func(x, a, b, c, d):
                return a * np.log(c * x + d) + b
        elif key in []:
            def func(x, a, b, c, d):
                return a / (1 + np.exp(-b * (c - x))) - d
        elif key in ['A4', 'A5', 'A6']:
            def func(x, a, b):
                return a * x + b
        else:
            func = None
            
        if func:
            popt, pcov = curve_fit(func, x, y)
            axs[i].plot(xn, func(xn, *popt), 'r-')
            models[key] = list(popt)
    
        i += 1
        
    return models

models = plot_series(series)
call("io.crossbar.demo.wpad.1.get_last")["values"][4:7]


Out[248]:
[141, 107, 55]

In [240]:
models


Out[240]:
{'A4': [14.553156146208956, 149.00664451859527],
 'A5': [19.624584728426772, 106.57807305486585],
 'A6': [11.825581395372446, 62.790697674553378]}

In [325]:
series_id = 22
series = call("io.crossbar.demo.wpad.objstore.get", "series", series_id)
print("ok, sample of size {} loaded".format(len(series['T'])))


ok, sample of size 4 loaded

In [326]:
plot_series(series)


Out[326]:
{'A4': [0.11107204985841113, 91.390426580004416],
 'A5': [0.2077777655840628, 60.312786927993329],
 'A6': [0.071992042315456903, 15.219972215697563]}

In [327]:
from sklearn import linear_model

X = np.matrix([series['A4'], series['A5'], series['A6']]).transpose()
y = series['T']

#clf = linear_model.LogisticRegression(C=1.)
clf = linear_model.Ridge(normalize=False)
clf.fit(X, y)


Out[327]:
Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, solver='auto', tol=0.001)

In [328]:
clf.coef_


Out[328]:
array([-1.43327193,  3.47251242,  6.07903917])

In [329]:
# Dynamically access current sensor values (A4, A5, A6)

call("io.crossbar.demo.wpad.1.get_last")["values"][4:7]


Out[329]:
[72, 45, 23]

In [334]:
# Predict target var based on current sensor values

values = call("io.crossbar.demo.wpad.1.get_last")["values"][4:7]
#clf.predict(values)[0]
clf.predict(values), 3.24094664 * values[0] +  0.8581397 * values[1] + 4.25890121 * values[2] + clf.intercept_


Out[334]:
(954.38968306533422, 1100.4001098804806)

In [324]:
# Here are the model coefficients:

#model = [list(row) for row in clf.coef_]
model = list(clf.coef_)
model.append(clf.intercept_)
model


Out[324]:
[3.2409466412999635,
 0.858139704268996,
 4.2589012098175321,
 -633.68376563794209]

In [270]:
# Upload the model coefficients

call("io.crossbar.demo.wpad.objstore.save", "model", model)


Out[270]:
10

In [ ]: