Linear Regression by Keras

Linear Regression is a primitive technique of forecasting in ML, lets try this in Keras…

Import Libraries

import keras
from keras.layers import Input, Dense
from keras.models import Model
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt
%matplotlib inline
import numpy

#Declare parameters
x_ = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
7.042,10.791,5.313,7.997,5.654,9.27,3.1])
y_ = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
2.827,3.465,1.65,2.904,2.42,2.94,1.3])

Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, and bias is a bias vector created by the layer (only applicable if use_bias is True)

Note for detail refer:  https://keras.io/layers/core/

inputs = Input(shape=(1,))

For activation function refer: https://keras.io/activations/
preds = Dense(1,activation=’linear’)(inputs)

model = Model(inputs=inputs,outputs=preds)
sgd=keras.optimizers.SGD()
model.compile(optimizer=sgd ,loss=’mse’)
model.fit(x_,y_, batch_size=1, verbose=1, epochs=10, shuffle=False)
plt.scatter(x_,y_,color=’black’)
plt.plot(x_,model.predict(x_), color=’blue’, linewidth=3)

Leave a Reply