How to use Keras Linear Regression for Multiple input-output?

I was trying to use this code. I put part of the parameter list, but as you see the error indicates that it's taking the first member of each list to put in the first row and second ones for the second row and so on ..

from pylab import *
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers

#Generate dummy data
data = [[45,45,200,300],[44.7,45.6,50,60],[9.9,10,11,12]]
y = data*5

#Define the model
def baseline_model():
   model = Sequential()
   model.add(Dense(1, activation = 'linear', input_dim = 1))
   sgd = optimizers.SGD(lr=0.2)
   model.compile(optimizer = sgd, loss = 'mean_squared_error', metrics = ['accuracy'])
   return model


#Use the model
regr = baseline_model()
regr.fit(data,y,epochs = 4,batch_size = 1)
plot(data, regr.predict(data), 'b', data,y, 'k.')

But was unsuccessful cause I get this error that less argoments were expected :

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 28 arrays: [array([[ 45. ], [ 44.7 ], [ 9.9 ], [ 65.5 ], [ 110. ], [ 2. ], [ 0.25], [ 13. ], [ 17. ]]), array([[ 45. ], [ 45.6 ],..

Topic keras tensorflow linear-regression neural-network

Category Data Science


The primary issue is y = data*5. That code programmatically creates synthetic targets. It might be better to explicitly create synthetic target values.

It is better to have both features and targets defined as numpy arrays than lists-of-lists.

Additionally, there has to be one input node for each regression feature.

Here is a revised version of your code:

import numpy as np
from pylab import *
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras        import optimizers

# Generate synthetic data
data = np.array([[45,45,200,300],[44.7,45.6,50,60],[9.9,10,11,12]])
y    = np.array([1, 2, 3]).reshape(-1, 1)

# Define the model
def baseline_model():
    model = Sequential()
    model.add(Dense(1, activation = 'linear', input_dim = data.shape[1]))
    sgd = optimizers.SGD(lr=0.2)
    model.compile(optimizer = sgd, loss = 'mean_squared_error', metrics = ['accuracy'])
    return model


# Use the model
regr = baseline_model()
regr.fit(data, y, epochs=4, batch_size=1)
plot(data, regr.predict(data), 'b', data,y, 'k.');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.