0
$\begingroup$

It's a silly problem, I know, but it's getting my nerves. Everything seems fine, but I cannot get the line to show on the plot.

I've put it in a public Google notebook, for your convenience.

t represents months, and f_t are sales (accumulated). I feed the model 12 months of data, and use the 13th month for prediction. Simple.

import random
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from matplotlib import pyplot as plt

muestra = []
# creamos las 13 muestras de acuerdo a la fórmula provista en la Situación Problemática.
for i in range(1,14):
  t = 3*i + 2*(random.uniform(-1, 1))
  muestra.append((i, t))


df = pd.DataFrame(muestra)
df.rename(columns={0:"t", 1:"f_t"}, inplace=True)

train = df.loc[:11]
test = df.loc[12:]

X_train = train.t.values.reshape(-1, 1)
y_train = train.f_t.values

X_test = test.t.values.reshape(-1, 1)
y_test = test.f_t.values

LR_model = LinearRegression()
LR_model.fit(X_train, y_train)
y_pred = LR_model.predict(X_test)

%matplotlib inline

plt.plot(X_test, y_pred, label="Regresión Lineal", color='g')
plt.scatter(X_train, y_train, label="Muestra",color='b') 
plt.scatter(X_test, y_test, label="Mes 13",color='r')
plt.legend()
plt.xlabel('Meses (t)')
plt.ylabel('Ventas (f(t))')
plt.title("Análisis en base a la técnica de regresión lineal simple")
plt.show()

Now, I get the scatter points, but not the regression line. What am I missing? Thank you.

$\endgroup$

1 Answer 1

1
$\begingroup$

You are trying to plot a single predicted point, When I believe you are actually looking to plot the fitted model. To do that you'll need the coef_ and intercept_ properties of the model. I have included a link to the documentation on this if you want to learn more.

%matplotlib inline
f_x = lambda x: (x * LR_model.coef_) + LR_model.intercept_
x_range = [0,13]
LR_model_y = list(map(f_x, x_range))
plt.plot(x_range,LR_model_y, label="Regresión Lineal", color='g')

https://scikit-learn.org/stable/modules/linear_model.html

$\endgroup$
1
  • $\begingroup$ Great! That solved it. Thank you so much, Levon. $\endgroup$ Nov 24, 2022 at 1:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.