# 编码线性回归时遇到问题

``````Y4 = iris_versicolor['sepal_width']
X4 = iris_versicolor[['petal_width']]
X4 = X4.copy()
X4['intercept'] = 1.
moindreCareCas4 = sm.OLS(Y4, X4).fit() # OLS = Ordinary Least Square
a4,b4 = moindreCareCas4.params['petal_width'],moindreCareCas4.params['intercept']

print(moindreCareCas4.params)

plt.plot(iris_versicolor.sepal_width,iris_versicolor.petal_width, "o")
plt.plot(np.arange(4),[a2*x+b2 for x in np.arange(4)])
plt.xlabel("petal_width")
plt.ylabel("sepal_width")
plt.show()
``````

``````import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(iris_versicolor[['sepal_width']], iris_versicolor[['petal_width']])

# Make predictions using the testing set
iris_versicolor_petal_width_pred = regr.predict(iris_versicolor[['sepal_width']])

# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(iris_versicolor[['petal_width']], iris_versicolor_petal_width_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(iris_versicolor[['petal_width']], iris_versicolor_petal_width_pred))

# Plot outputs
plt.scatter(iris_versicolor[['sepal_width']], iris_versicolor[['petal_width']],  color='black')
plt.plot(iris_versicolor[['sepal_width']], iris_versicolor_petal_width_pred, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()
``````