赞
踩
看 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
#导入数据
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)
#归一化
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)
#搭建模型
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')
#回调函数+训练
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)
#画图
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)
#训练
model.evaluate(x_test_scaled,y_train)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。