任务描述
本关任务:编写一个梯度下降的小程序,输出损失函数值。
编程要求
请仔细阅读右侧代码,结合相关知识,在 Begin-End 区域内进行代码补充,输出进行 1-10 次梯度下降后的损失函数值。
#********** Begin **********#
# 梯度下降函数:将None处替换为你写的代码
def gradient_descent(x_i, y_i, w, b, alpha):
dw =-2 * error(w, b, x_i, y_i)* x_i
db =-2 * error(w, b, x_i, y_i)
w =w - alpha * dw
b = b - alpha * db
return w, b
#********** End **********#
# read data
data_path ='task1/train.csv'
data = pd.read_csv(data_path)
# select property
data = data[['GrLivArea', 'SalePrice']]
# separate train and test data
train = data[:1168]
test = data[1168:]
# a fixed alpha slows down learning; here we use 10 iterations to show the error is decreasing\n",
x = test['GrLivArea'].tolist()
y = test['SalePrice'].tolist()
num_iterations = 10
alpha = 0.0000001
random.seed(0)
w, b = [random.random(), 0]
#********** Begin **********#
# 梯度下降并输出损失函数值:将None处替换为你写的代码
for i in range(num_iterations):
for x_i, y_i in zip(x, y):
w, b = gradient_descent(x_i, y_i, w, b, alpha)
print(sum_of_squared_errors(w, b, x, y))
#********** End **********#
任务描述
本关任务:编写一个小程序求解多元线性模型,并输出训练集与测试集的 RMSE 值。
编程要求
请仔细阅读右侧代码,结合相关知识,在 Begin-End 区域内进行代码补充,输出训练集与测试集的 RMSE 值。
#********** Begin **********#惩罚权重设为30
# 输出训练集合预测误差:替换补全None的部分
clf = Ridge(alpha=30)
clf.fit(x,y)
y_pred = clf.predict(x)
print(math.sqrt(mean_squared_error(y, y_pred)))
#********** End **********#
任务描述
本关任务:使用 Keras 建立回归模型。
编程要求
请仔细阅读右侧代码,结合相关知识,在 Begin-End 区域内进行代码补充,使用 Keras 建立回归模型。SalePrice 为目标变量。
# filter data
predictors = data.select_dtypes(exclude=['object'])
cols_with_no_nans = []
for col in predictors.columns:
if not data[col].isnull().any():
cols_with_no_nans.append(col)
data_filtered = data[cols_with_no_nans]
data = data_filtered[['MSSubClass', 'LotArea', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd', 'Fireplaces', 'GarageCars', 'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'MoSold', 'YrSold', 'SalePrice']]
# separate train and test
train = data[:1168]
test = data[1168:]
y = train[['SalePrice']]
x = train[['MSSubClass', 'LotArea', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd', 'Fireplaces', 'GarageCars', 'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'MoSold', 'YrSold']]
# define model
NN_model = Sequential()#定义一个神经网络模型
#********* Begin *********#
# 把所有标None的部分填写替换
# input layer
# 添加input layer,使用128个神经元,用正态方式初始化,设置正则项为l2(权值0.1),输入维度根据x的维度来定,采用relu作为激活函数
NN_model.add(Dense(128,#全连接层
kernel_initializer='normal',#初始化权值
kernel_regularizer=l2(0.1),#设置正则项
input_dim = x.shape[1],#定义输入维度
activation='relu'))#设置激活函数
# hidden layers
# 添加两个layer,每个layer使用256个神经元,用正态方式初始化,设置正则项为l2(权值0.1),采用relu作为激活函数
NN_model.add(Dense(256, kernel_initializer='normal', kernel_regularizer=l2(0.1), activation='relu'))
NN_model.add(Dense(256, kernel_initializer='normal', kernel_regularizer=l2(0.1), activation='relu'))
# output layer
# 添加输出layer,使用一个神经元,采用linear激活函数
NN_model.add(Dense(1, kernel_initializer='normal',activation='linear'))
# compile and train network
NN_model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_squared_error'])#使用自适应调节学习率adam
NN_model.fit(x, y, epochs=500, batch_size=32, validation_split = 0.2,verbose=0)#训练次数、批次大小、验证和训练集合划分比例
# evaluate on test set
test_x = test[['MSSubClass', 'LotArea', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd', 'Fireplaces', 'GarageCars', 'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'MoSold', 'YrSold']]
test_y = test[['SalePrice']]
test_y_pred = NN_model.predict(test_x)
# return test error
test_error = math.sqrt(mean_squared_error(test_y, test_y_pred))
return test_error
#********* End *********#
注:内容只做参考和分享,未经允许不可传播,侵权立删