контурный график для прогнозирования регрессии с фиксированными входными переменными - PullRequest
0 голосов
/ 14 ноября 2018

Я хочу создать контурную диаграмму для прогноза с несколькими функциями. Остальные значения должны быть зафиксированы, чтобы построить 2 интересных значения. К сожалению, итоговая матрица имеет одинаковое значение на всех позициях вместо ожидаемого.

Я думаю, что с моими матрицами что-то не так, но я не нахожу ошибку.

[...]
f_learn = [x_1,x_2,x_3,x_4]
r_lear = [r_1]

clf = svm.MLPRegressor(...)
clf.fit(f_learn,r_learn)
[...]

x_1 = np.linspace(1, 100, 100)
x_2 = np.linspace(1, 100, 100)
X_1, X_2 = np.meshgrid(x_1, x_2)

x_3 = np.full( (100,100), 5).ravel()
x_4 = np.full( (100,100), 15).ravel()

predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3,x_4])
prediction = clf.predict(predict_matrix.T)

prediction_plot = prediction.reshape(X_1.shape)

plt.figure()
    cp = plt.contourf(X_1, X_2, prediction_plot, 10)
    plt.colorbar(cp)
    plt.show()

Если я тестирую матрицу построчно, я получаю правильные результаты. Однако это не сработает, если я соберу их вместе таким образом.

Редактировать: ошибка при копировании кода

Пример с данными. Все ответы 7,5 и не разные; (

import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model

f_learn =  np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
r_learn =  np.array([6,7,8,9])

reg = linear_model.LinearRegression()
reg.fit (f_learn, r_learn)

x_1 = np.linspace(0, 20, 10)
x_2 = np.linspace(0, 20, 10)
X_1, X_2 = np.meshgrid(x_1, x_2)

x_3 = np.full( (10,10), 5).ravel()
x_4 = np.full( (10,10), 2).ravel()

predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])
prediction = reg.predict(predict_matrix.T)

prediction_plot = prediction.reshape(X_1.shape)

plt.figure()
cp = plt.contourf(X_1, X_2, prediction_plot, 10)
plt.colorbar(cp)
plt.show()

Результат

Ответы [ 3 ]

0 голосов
/ 14 ноября 2018

Следующий код должен дать вам контурный график, который вы хотите.

from sklearn.datasets import make_regression

f_learn, r_learn = make_regression(20,4)

reg = linear_model.LinearRegression()
reg.fit (f_learn, r_learn)

x_1 = np.linspace(-2, 2, 10)
x_2 = np.linspace(-2, 2, 10)
X_1, X_2 = np.meshgrid(x_1, x_2)


x_3 = np.full( (10,10), 0.33).ravel()
x_4 = np.full( (10,10), 0.99).ravel()

predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])
prediction = reg.predict(predict_matrix.T)

prediction_plot = prediction.reshape(X_1.shape)

plt.figure()
cp = plt.contourf(X_1, X_2, prediction_plot, 10)
plt.colorbar(cp)
plt.show()
0 голосов
/ 14 ноября 2018

В ваших игрушечных данных есть 4 примера с одинаковыми значениями характеристик и разными метками.Линейная регрессия ничему от этого не научилась.Вы можете проверить это:

>>> reg.coef_
[0. 0. 0. 0.]

Возможно, это также относится к вашим реальным данным.Что особенности x_1, x_2 не имеют значения.Проверьте reg.coef_, не слишком ли малы значения для объектов x_1, x_2.

Я изменил данные игрушки, и график работает.

import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model

# f_learn =  np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
# r_learn =  np.array([6,7,8,9])
f_learn = np.arange(20.).reshape(5, 4)
f_learn += np.random.randn(5, 4)
r_learn = f_learn[:, 0] + 2 * f_learn[:, 1] + 3 * f_learn[:, 2] + 4 * f_learn[:, 3]

reg = linear_model.LinearRegression()
reg.fit(f_learn, r_learn)
print(reg.coef_)

x_1 = np.linspace(0, 20, 10)
x_2 = np.linspace(0, 20, 10)
X_1, X_2 = np.meshgrid(x_1, x_2)

x_3 = np.full( (10,10), 5).ravel()
x_4 = np.full( (10,10), 2).ravel()

predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])
prediction = reg.predict(predict_matrix.T)

prediction_plot = prediction.reshape(X_1.shape)

plt.figure()
cp = plt.contourf(X_1, X_2, prediction_plot, 10)
plt.colorbar(cp)
plt.show()

enter image description here

0 голосов
/ 14 ноября 2018

Попробуйте что-нибудь подобное. Некоторые комментарии в коде

x_1 = np.linspace(1, 100, 100)
x_2 = np.linspace(1, 100, 100)
X_1, X_2 = np.meshgrid(x_1, x_2)

# Why the shape was (1000, 100)?
x_3 = np.full((100, 100), 5).ravel() 
x_4 = np.full((100, 100),  15).ravel()

# you should use X_1.ravel() to make it column vector (it is one feature)
# there was x_3 insted of x_4
predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])  
prediction = clf.predict(predict_matrix.T)

prediction_plot = prediction.reshape(X_1.shape)

plt.figure()
cp = plt.contourf(X_1, X_2, prediction_plot, 10)
plt.colorbar(cp)
plt.show()
...