使用Python进行回归

使用Python进行回归

本文介绍了使用Python进行回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变量:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split


np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10


X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)


def part1_scatter():
    %matplotlib notebook
    plt.figure()
    plt.scatter(X_train, y_train, label='training data')
    plt.scatter(X_test, y_test, label='test data')
    plt.legend(loc=4);

以及以下问题:

在训练数据X_train上写一个适合多项式LinearRegression模型的函数,以度为1、3、6和9.(在sklearn.preprocessing中使用PolynomialFeatures创建多项式特征,然后拟合线性回归模型)对于每个在模型中,在x = 0到10的区间内找到100个预测值(例如np.linspace(0,10,100)),并将其存储在numpy数组中.此数组的第一行应对应于在阶数1,第二行阶数3,第三行阶数6和第四行阶数9训练的模型的输出.

Write a function that fits a polynomial LinearRegression model on the training data X_train for degrees 1, 3, 6, and 9. (Use PolynomialFeatures in sklearn.preprocessing to create the polynomial features and then fit a linear regression model) For each model, find 100 predicted values over the interval x = 0 to 10 (e.g. np.linspace(0,10,100)) and store this in a numpy array. The first row of this array should correspond to the output from the model trained on degree 1, the second row degree 3, the third row degree 6, and the fourth row degree 9.

这是我的代码,但无法解决:

This is my code, but it don't work out:

def answer_one():
    from sklearn.linear_model import LinearRegression
    from sklearn.preprocessing import PolynomialFeatures

    np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
results = []
pred_data = np.linspace(0,10,100)
degree = [1,3,6,9]
y_train1 = y_train.reshape(-1,1)

for i in degree:
    poly = PolynomialFeatures(degree=i)
    pred_poly1 = poly.fit_transform(pred_data[:,np.newaxis])
    X_F1_poly = poly.fit_transform(X_train[:,np.newaxis])
    linreg = LinearRegression().fit(X_F1_poly, y_train1)
    pred = linreg.predict(pred_poly1)
    results.append(pred)

    dataArray = np.array(results).reshape(4, 100)

    return dataArray

我收到此错误:

    line 58      for i
in degree:      ^  IndentationError: unexpected
indent

你能告诉我问题出在哪里吗?

Could you tell me where the problem is?

推荐答案

行首

n = 15

您停止了识别.因此,该部分未被识别为功能.这可以通过在从n = 15开始的所有行上放置4个空格来解决.

You stopped with identing. So that part isn't recognized as the function. This can be solved by putting 4 spaces on all lines from n = 15 onwards.

这篇关于使用Python进行回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:10