Published
Edited
Jan 24, 2021
1 star
Insert cell
md`# House Price Prediction - Tensorflow.js`
Insert cell
tf = require('@tensorflow/tfjs')
Insert cell
file = FileAttachment("040 kc-house-data.csv")
Insert cell
dataset = file.csv()
Insert cell
xTrainRaw = {
const selectedXKeys = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'sqft_above', 'sqft_basement'];
const xTrainRawArray = dataset.map(data => {
return Object.keys(data).filter(key => selectedXKeys.includes(key)).map(key => {
return parseFloat(data[key])
})
})
const xTrainRawTensor = tf.tensor(xTrainRawArray)
return xTrainRawTensor;
}
Insert cell
xMin = xTrainRaw.min()
Insert cell
xMax = xTrainRaw.max()
Insert cell
minMaxNormalizer = (tensor) => {
return tensor.sub(xMin).div(xMax.sub(xMin));
}
Insert cell
xTrain = minMaxNormalizer(xTrainRaw)
Insert cell
yTrain = tf.tensor(dataset.map(data => parseFloat(data['price'])))
Insert cell
mutable history = ({epoch: 0, loss: 0, val_loss: 0});
Insert cell
model = {
const model = tf.sequential({layers: [
tf.layers.dense({units: 100, inputShape: [7], activation: 'relu'}),
tf.layers.dense({units: 100, activation: 'relu'}),
tf.layers.dense({units: 100, activation: 'relu'}),
tf.layers.dense({units: 1, activation: 'linear'})
]})
model.compile({optimizer: 'adam', loss: 'meanSquaredError'})
await model.fit(xTrain, yTrain, {epochs: 1000, validationSplit: 0.2, batchSize: 50, callbacks: {onEpochEnd: (epoch, {val_loss, loss}) => {
mutable history = {epoch, loss, val_loss}
}}})
return model;
}
Insert cell
model.getWeights().toString()
Insert cell
xPredict = {
const predictData = {
'bedrooms': 3,
'bathrooms': 1,
'sqft_living': 1180,
'sqft_lot': 5650,
'floors': 1,
'sqft_above': 1180,
'sqft_basement': 0
}
const predictDataArray = Object.values(predictData);
const predictDataTensor = tf.tensor([predictDataArray]);
const predictDataTensorNormalized = minMaxNormalizer(predictDataTensor)
return predictDataTensorNormalized;
}
Insert cell
yPredict = model.predict(xPredict).toString()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more