EJEMPLO DE REGRESION LINEAL
EJEMPLO DE REGRESION LINEAL
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Datos de ejemplo
np.random.seed(42)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
plt.scatter(X, y)
plt.title('Datos de ejemplo para regresión lineal')
plt.xlabel('Variable independiente (X)')
plt.ylabel('Variable dependiente (y)')
plt.show()
# Inicializar el modelo de regresión lineal
model = LinearRegression()
# Entrenar el modelo
model.fit(X, y)
# Generar datos para predecir
X_new = np.array([[0], [2]])
# Realizar predicciones
y_pred = model.predict(X_new)
plt.scatter(X, y, label='Datos de ejemplo')
plt.plot(X_new, y_pred, 'r-', label='Línea de regresión')
plt.title('Regresión Lineal')
plt.xlabel('Variable independiente (X)')
plt.ylabel('Variable dependiente (y)')
plt.legend()
plt.show()
print('Coeficiente (pendiente):', model.coef_)
print('Término independiente:', model.intercept_)
from sklearn.metrics import mean_squared_error
print('Error cuadrático medio:', mean_squared_error(y, model.predict(X)))
Comentarios
Publicar un comentario