当前位置:   article > 正文

波士顿房价预测_波士顿房价预测实验报告

波士顿房价预测实验报告

看 https://www.bilibili.com/video/BV1Z541167M3?p=24 做的笔记

导入库

#导入库
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

导入数据

#导入数据
from sklearn.datasets import fetch_california_housing
housing=fetch_california_housing()
#划分训练集
from sklearn.model_selection import train_test_split
x_train_all,x_test,y_train_all,y_test=train_test_split(housing.data,housing.target,random_state=7,test_size=0.3)
x_train,x_valid,y_train,y_valid=train_test_split(x_train_all,y_train_all,random_state=11)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

归一化

#归一化
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
x_train_scaled=scaler.fit_transform(x_train)
x_valid_scaled=scaler.transform(x_valid)
x_test_scaled=scaler.transform(x_test)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

搭建模型

#搭建模型
model=keras.models.Sequential([
    keras.layers.Dense(30,activation='relu',input_shape=x_train.shape[1:]),
    keras.layers.Dense(1)

])
model.compile(loss='mean_squared_error',optimizer='sgd')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

回调函数+训练

#回调函数+训练
callbacks=[keras.callbacks.EarlyStopping(patience=5,min_delta=1e-3)]
history=model.fit(x_train_scaled,y_train,
                  validation_data=(x_valid_scaled,y_valid),
                  epochs=100,
                  callbacks=callbacks)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

画图

#画图
def plot_learning_curves(history):
    pd.DataFrame(history.history).plot(figsize=(8,5))
    plt.grid(True)#网格
    plt.gca().set_ylim(0,1)#坐标轴范围
    plt.show()
plot_learning_curves(history)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

训练

#训练
model.evaluate(x_test_scaled,y_train)
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/94552
推荐阅读
相关标签
  

闽ICP备14008679号