from sklearn.linear_model import LinearRegression
import numpy as np
# 创建并拟合模型
X = [[6], [8], [10], [15], [18]]
y = [[20], [25], [35], [50], [60]]
model = LinearRegression()//定义对象
model.fit(X, y) //训练模型
print(model.coef_, model.intercept_)
predict_data = np.array([12]).reshape(-1, 1)#转换2维, 和训练数据维度保持一致
predict_result = model.predict(predict_data)//预测
print('预测12英寸匹萨价格:$%.2f' % predict_result)
from sklearn.linear_model import LinearRegression
X = [[6], [8], [10], [15], [18]]
y = [[20], [25], [35], [50], [60]]
X_test = [[12],[14],[16]]
y_test = [[40],[45],[55]]
model = LinearRegression()
model.fit(X, y)
print(model.score(X_test, y_test))
输出结果:
0.9540273803329865
from sklearn.linear_model import LinearRegression
X = [[6, 2], [8, 1.5], [10, 0.5], [15, 2], [18, 0.5]]
y = [[22], [25], [32], [55], [58]]
model = LinearRegression()
model.fit(X, y)
print(model.coef_,' ',model.intercept_)
X_test = [[8, 2], [9, 0.5], [11, 2], [16, 2], [12, 0.5]]
y_test = [[28], [26], [36], [60], [36]]
predictions = model.predict(X_test)
for i, prediction in enumerate(predictions):
print('Predicted: %s, Target: %s' % (prediction, y_test[i]))
print('R-squared: %.2f' % model.score(X_test, y_test))
y = ax + bx2 +c
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2) # 定义多项式扩展类,参数指定要扩展的阶数, 添加2次方特征
poly.fit(X) #不是一个训练的过程,而是一个适配的过程,fit之后,然后才调用各种API方法
#对数据集X进行多项式扩展,即进行多项式转换
X2 = poly.transform(X)
# 可以令fit与transofrm两步一起完成。
X2= poly.fit_transform(X)
lin_reg = LinearRegression()
lin_reg.fit(X2, y)
y_pred = lin_reg.predict(X2)
plt.scatter(x, y)
plt.scatter(x, y_pred, color = 'r')
plt.show()