Skip to content

Instantly share code, notes, and snippets.

@curiousily
curiousily / Co Hapi Mongoose Generator Wiring.js
Last active August 29, 2015 14:11
Wire up co, hapi, mongoose and node 0.11.9+ --harmony
var Mongoose = require('mongoose')
var Hapi = require('hapi')
var Co = require('co')
Mongoose.connect('mongodb://localhost/mytestdb')
var userSchema = Mongoose.Schema({
name: String
})
@curiousily
curiousily / linear-regression-in-tensorflow.js
Created June 20, 2018 17:45
Create a Simple Linear Regression model in TensorFlow.js that given some number from the Fibonacci sequence predicts the next one while only running in the browser!
// What is a Tensor?
const myFirstTensor = tf.scalar(42)
console.log(myFirstTensor)
myFirstTensor.print()
const oneDimTensor = tf.tensor1d([1, 2, 3])
oneDimTensor.print()
data = OrderedDict(
amount_spent = [50, 10, 20, 5, 95, 70, 100, 200, 0],
send_discount = [0, 1, 1, 1, 0, 0, 0, 0, 1]
)
df = pd.DataFrame.from_dict(data)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def loss(h, y):
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
X = df['amount_spent'].astype('float').values
y = df['send_discount'].astype('float').values
def predict(x, w):
return sigmoid(x * w)
def print_result(y_hat, y):
print(f'loss: {np.round(loss(y_hat, y), 5)} predicted: {y_hat} actual: {y}')
y_hat = predict(x=X[0], w=.5)
for w in np.arange(-1, 1, 0.1):
y_hat = predict(x=X[0], w=w)
print(loss(y_hat, y[0]))
def fit(X, y, n_iter=100000, lr=0.01):
W = np.zeros(X.shape[1])
for i in range(n_iter):
z = np.dot(X, W)
h = sigmoid(z)
gradient = np.dot(X.T, (h - y)) / y.size
W -= lr * gradient
return W
def predict(X, W):
return sigmoid(np.dot(X, W))