I have data of the following kind:
x1 x2 y
0 0 1 1
1 0 2 2
2 0 3 3
3 0 4 4
4 1 1 4
5 1 2 8
6 1 3 12
7 1 4 16
Is it possible to construct a single machine learning algorithm in python/scikit-learn by defining column x1
in such a way that a simple linear regression should give predict(x1=0, x2=5) = 5
and predict(x1=1, x2=5) = 20
. My actual problem has multiple values of x1
.
To illustrate the problem better: I have the following code with one hot encoder and it doesn't seem to give the accuracy of training the data separately.
import pandas as pd
from sklearn.linear_model import LinearRegression
# Dataframe with x1 = 0 and linear regression gives a slope of 1 as expected
df = pd.DataFrame(data=[{'x1': 0, 'x2': 1, 'y': 1},
{'x1': 0, 'x2': 2, 'y': 2},
{'x1': 0, 'x2': 3, 'y': 3},
{'x1': 0, 'x2': 4, 'y': 4}
],
columns=['x1', 'x2', 'y'])
X = df[['x1', 'x2']]
y = df['y']
reg = LinearRegression().fit(X, y)
print(reg.predict(np.array([[0, 5]]))) # Output is 5 as expected
# Dataframe with x1 = 1 and linear regression gives a slope of 5 as expected
df = pd.DataFrame(data=[{'x1': 1, 'x2': 1, 'y': 4},
{'x1': 1, 'x2': 2, 'y': 8},
{'x1': 1, 'x2': 3, 'y': 12},
{'x1': 1, 'x2': 4, 'y': 16}
],
columns=['x1', 'x2', 'y'])
X = df[['x1', 'x2']]
y = df['y']
reg = LinearRegression().fit(X, y)
print(reg.predict(np.array([[1, 5]]))) # Output is 20 as expected
# Combine the two data frames x1 = 0 and x1 = 1
df = pd.DataFrame(data=[{'x1': 0, 'x2': 1, 'y': 1},
{'x1': 0, 'x2': 2, 'y': 2},
{'x1': 0, 'x2': 3, 'y': 3},
{'x1': 0, 'x2': 4, 'y': 4},
{'x1': 1, 'x2': 1, 'y': 4},
{'x1': 1, 'x2': 2, 'y': 8},
{'x1': 1, 'x2': 3, 'y': 12},
{'x1': 1, 'x2': 4, 'y': 16}
],
columns=['x1', 'x2', 'y'])
X = df[['x1', 'x2']]
y = df['y']
reg = LinearRegression().fit(X, y)
print(reg.predict(np.array([[0, 5]]))) # Output is 8.75
print(reg.predict(np.array([[1, 5]]))) # Output is 16.25
# use one hot encoder
df = pd.get_dummies(df, columns=["x1"], prefix=["x1"])
X = df[['x1_0', 'x1_1', 'x2']]
y = df['y']
reg = LinearRegression().fit(X, y)
print(reg.predict(np.array([[1, 0, 5]]))) # Output is 8.75
print(reg.predict(np.array([[0, 1, 5]]))) # Output is 16.25
How can I use pandas and sklearn for the combined data to get the same accuracy using one machine learning model?
datascience
. This is one good link that may help you: scikit-learn.org/stable/tutorial/basic/tutorial.html $\endgroup$x1
) which qualitatively changes the trend of the data. In the example I gave, the ML algorithm must giveslope = 1
whenx1=0
andslope=4
whenx1=1
. Is that possible to do with a single ML algorithm or breaking up the data into two training sets is the only alternative? $\endgroup$