DataWhale集成学习Task02 回归问题
作业: 波士顿房价的预测问题
1.使用sklearn的线性回归模型
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn import preprocessing
data = load_boston()
data_pd = pd.DataFrame(data.data,columns=data.feature_names)
data_pd['price'] = data.target
data_pd = data_pd[['LSTAT','PTRATIO','RM','price']]
y = np.array(data_pd['price'])
data_pd=data_pd.drop(['price'],axis=1)
X = np.array(data_pd)
train_X,test_X,train_Y,test_Y = train_test_split(X,y,test_size=0.2)
linreg = LinearRegression()
linreg.fit(train_X,train_Y)
y_predict = linreg.predict(test_X)
metrics.mean_squared_error(y_predict,test_Y)
2.numpy 写线性回归
import numpy as np
import matplotlib.pyplot as plt
def load_data():
datafile = 'housing.data'
data = np.fromfile(datafile, sep=' ')
data = data.reshape([-1, 14])
offset = int(data.shape[0]*0.8)
train_data = data[:offset]
maximums, minimums, avgs = train_data.max(axis=0), train_data.min(axis=0), train_data.sum(axis=0) / train_data.shape[0]
for i in range(14):
data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])
train_data = data[:offset]
test_data = data[offset:]
return train_data, test_data
class Network(object):
def __init__(self, num_of_weight):
self.w = np.random.randn(num_of_weight, 1)
self.b = 0.
def forword(self, x):
z = np.dot(x, self.w) + self.b
return z
def loss(self, z, y):
error = z - y
cost = error * error
cost = np.mean(cost)
return cost
def gradient(self, x, y):
z = self.forword(x)
gradient_w = np.mean((z - y)*x, axis=0)
gradient_w = gradient_w[:, np.newaxis]
gradient_b = np.mean((z - y), axis=0)
return gradient_w, gradient_b
def update(self, gradient_w, gradient_b, eta=0.01):
self.w = self.w - eta*gradient_w
self.b = self.b - eta*gradient_b
def train(self, train_data, num_epcches, batch_size=10, eta=0.01):
n = len(train_data)
print(n)
losses = []
for epoch_id in range(num_epcches):
np.random.shuffle(train_data)
mini_batches = [train_data[k:k+batch_size] for k in range(0, n, batch_size)]
for iter_id, mini_batch in enumerate(mini_batches):
x = mini_batch[:, :-1]
y = mini_batch[:, -1:]
z = self.forword(x)
loss = self.loss(z, y)
gradient_w, gradient_b = self.gradient(x, y)
self.update(gradient_w, gradient_b, eta)
losses.append(loss)
print('Epoch{:3d} / iter {:3d}, loss = {:.4f}'.format(epoch_id, iter_id, loss))
return losses
train_data, test_data = load_data()
net = Network(13)
losses = net.train(train_data, batch_size=50, num_epcches=100, eta=0.01)
plot_x = np.arange(len(losses))
plot_y = np.array(losses)
plt.plot(plot_x, plot_y)
plt.show()
|