Scikit Learn多元回归模型

2024-04-16 12:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以针对不同的特征使用不同的模型,例如,当我想从收入中值预测房价时,我会使用线性模型,但当我想从坐标预测房价时,最好使用k-近邻。你知道吗

import sklearn
import numpy as np

X_housing_income = np.array([l[0] for l in X_housing].reshape(-1,1)
X_housing_latitude = np.array([l[1] for l in X_housing].reshape(-1,1)
X_housing_longitude = np.array([l[2] for l in X_housing].reshape(-1,1)

lin_reg_income = sklearn.linear_model.LinearRegression()
lin_reg_income.fit(X_housing_income,y_housing)

knn_reg_latitude = sklearn.neighbors.KNeighborsRegression()
knn_reg_latitude.fit(X_housing_latitude,y_housing)

knn_reg_longitude = sklearn.neighbors.KNeighborsRegression()
knn_reg_longitude.fit(X_housing_longitude,y_housing)

prediction_income = lin_reg_income.predict(some_income)
prediction_latitude = knn_reg_latitude.predict(some_latitude)
prediction_longitude = knn_reg_longitude.predict(some_longitude)

prediction_mean = (prediction_income + prediction_latitude + prediction_longitude) / 2

有没有一种方法可以在scikit learn中结合这一点,还是由我自己来实现更好?你知道吗


Tags: infornpsklearnregarrayfitprediction
2条回答

你必须自己做,但是看看我写的关于处理丢失数据的文章-https://colab.research.google.com/drive/1ZyyppDx72d6bRZc2q4ksqrmHsXHvkGI6

最后,我创建了一个类,用pandas来检测给定样本中哪些条目是NaN(每次只需将房价设置为NaN),然后选择一组合适的模型。你知道吗

目前,它只选择一个小的ANN作为模型(但是你可以很容易地改变它),平均技术需要调整,但是它应该让你开始走上正确的道路

我只是自己实现的,因为在scikit learn中似乎没有这样的东西:

class MultiModelRegressor(RegressorMixin):
    def __init__(self,models):
        self.models = models
    def fit(self, X, y):
        X_ = X.copy().reshape(X.shape[1], X.shape[0])
        y_ = y.copy().reshape(-1, y.shape[0])
        for features, labels, model in [(a,b,c) for a in X_ for b in y_ for c in self.models]:
            if not model == None:
                model.fit(features.reshape(-1,1), labels.reshape(-1,1))
    def predict(self, X):
        X_ = X.copy().reshape(X.shape[1], X.shape[0])
        prediction = np.empty(X.shape[0])
        for features, model in [(a,b) for a in X_ for b in self.models]:
            if not model == None:
                prediction = (np.array([a+b for a in prediction for b in model.predict(features.reshape(-1,1))] ) / 2)
        return prediction.reshape(X.shape[0])

它并不完美,但我真的不明白为什么像这样的东西还没有在scikit学习,我的意思是它相当有用,不是吗?你知道吗

相关问题 更多 >