步骤:
1. 加载数据集:
import pandas as pd
# 用pd.read_scv 加载scv数据
pd.read_scv(file, sep)
california_housing_dataframe = pd.read_csv("https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv", sep=',')
# 用 reindex函数 随机化所有数据
# 用np.random.permutation()函数随机排列dataframe的index
california_housing_dataframe = california_housing_dataframe.reindex(np.random.permutation(california_housing_dataframe.index))
# 修改房价为以千为单位便于调节
california_housing_dataframe = california_housing_dataframe["median_house_value"] /= 1000.0
# 测试数据,输出摘要
california_housing_dataframe.describe()
2. 配置模型参数:
# 原理:
# 将房价 median_house_value 作为预测目标
# 将房间数 total_rooms 作为特征
# 采用Estimator API提供的 LinearRegressor接口
-
定义特征并配置特征列:
特征有分类数据和数值数据两种
本次使用的特征total-rooms 是数值数据
特征列:仅储存对特征数据的描述,不包含数据本身。# 获取特征数据:total-rooms my_feature = california_housing_dataframe[["total-rooms"]] # 定义特征列 feature_columns = [tf.feature_column.numeric_column("total_rooms")]
-
定义目标:
获取目标# 获取 median_house_value targets = california_housing_dataframe["median_house_value"]
-
配置 LinearRegressor:
用LinearRegressor配置线性回归模型
用GradientDescentOptimizer训练模型
用clip_gradients_by_norm 配置梯度裁剪,以免梯度过大# 定义训练: my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001) my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0) # 定义线性模型: # 采用 my_optimizer 训练 # feature_columns 是特征列 linear_regressor = tf.estimator.LinearRegressor(feature_columns = feature_columns, optimizer = my_optimizer)
-
定义输入函数:
LinearRegressor是一个框架,没有数据输入, 因此需要输入函数来进行数据输入,告诉tensorflow如何进行预处理,以及在训练期间如何批处理,随机处理及重复数据步骤:
- 将Pandas的Series 转化为Numpy的字典
- 构造Tensorflow的 Dataset API 构造dataset对象
- 将数据拆分为 batch_size 大小的多批
- 循环 num_epochs 次,如果num_epochs为0则循环无数次
- shuffle 如果为True,则对数据进行随机处理
- 迭代器,传递下一批数据
# 定义函数 def my_input_function(features, targets, batch_size = 1, shuffle = True, num_epochs = None) # 将pandas的series类型转化为字典 features = {key: np.array(value) for key, value in dict(features).items()} # 创建dataset类型 ds = Dataset.from_tensor_slices((features, targets)) # 数据最多占用2G空间 ds = ds.batch(batch_size).repeat(num_epochs) # shuffle if shuffle: ds = ds.shuffle(buffer_size = 10000) # 返回数据集 features, labels = ds.make_one_iterator().get_next() return features, labels
-
训练模型:
-
调用 train()训练模型
-
将my_input_function 封装在 lambda 中
# 训练模型 _ = linear_regressor.train(input_fn = lambda:my_input_fn(my_feature, targets), steps=100)
-
-
评估模型:
做一次预测# 获取预测所需数据 prediction_input_function = lambda: my_input_fn(my_feature, targets, num_epochs=1, shuffle=False) # 进行预测 predictions = linear_regressor.predict(input_fn=prediction_input_fn) # 将预测结果转化为array形式便于计算MSE等 predictions = np.array([item['predictions'][0] for item in predictions]) # 计算MSE和RMSE并输出: mean_squared_error = metrics.mean_squared_error(predictions, targets) root_mean_squared_error = math.sqrt(mean_squared_error) print("Mean Squared Error (on training data): %0.3f" % mean_squared_error) print("Root Mean Squared Error (on training data): %0.3f" % root_mean_squared_error) # 为了评估效果,打印labels的max和min min_house_value = california_housing_dataframe["median_house_value"].min() max_house_value = california_housing_dataframe["median_house_value"].max() min_max_difference = max_house_value - min_house_value print("Min. Median House Value: %0.3f" % min_house_value) print("Max. Median House Value: %0.3f" % max_house_value) print("Difference between Min. and Max.: %0.3f" % min_max_difference) print("Root Mean Squared Error: %0.3f" % root_mean_squared_error) # 用pd.describe()进行评价 # 创建一个dataframe类型容器 calibration_data = pd.DataFrame() # 将预测值和目标值分别作为两列输入到dataframe容器中 calibration_data["predictions"] = pd.Series(predictions) calibration_data["targets"] = pd.Series(targets) # 输出discribe来观察预测值和目标值之间的关系 print(calibration_data.describe()) # 通过绘制曲线来观察预测值和目标值之间的关系 # 获取数据 sample = california_housing_dataframe.sample(n=300) # 定义横轴范围 x_0 = sample["total_rooms"].min() x_1 = sample["total_rooms"].max() # 获取线性回归的权重Weight和偏置值bias weight = linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0] bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights') # 用两端点确定拟合的直线 y_0 = weight * x_0 + bias y_1 = weight * x_1 + bias # 绘制直线 plt.plot([x_0, x_1], [y_0, y_1], c='r') # 定义坐标轴 plt.ylabel("median_house_value") plt.xlabel("total_rooms") # 绘制原数据散点图 plt.scatter(sample["total_rooms"], sample["median_house_value"]) # 显示 plt.show()
网友评论