keras实现函数拟合-Boston房价的预测

#2021.10.16 HIT ATCI LZH
#keras实现Boston房价的预测
import keras
from keras.losses import mean_squared_error
import tensorflow as tf
import numpy as np
from keras.models import Sequential#定义模型的类型,Keras 提供了两种类型的模型:序列和模型类的API,Keras 提供各种类型的神经网络层
from keras.layers import Activation
from keras.layers import Dense
import matplotlib.pyplot as plt #数据可视化
from sklearn import datasets #用于加载数据
from sklearn.model_selection import train_test_split #sklearn模块用于获取数据集和预处理数据集,并将其分为训练集和预测集
from sklearn.preprocessing import MinMaxScaler #用于归一化
import pandas as pd #可以用来分析数据集
import seaborn as sns
from tensorflow.python.training.input import batch #用于数据可视化
from sklearn.metrics import r2_score
#加载数据集并创建Pandas数据帧来分析数据
boston = datasets.load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)#这部分是采用pd库进行数据处理
df['target'] = boston.target
print(df.describe())


X_train, X_test, y_train, y_test = train_test_split(df[['RM',
'LSTAT', 'PTRATIO']],df[['target']], test_size=0.3,
random_state = 0)  #测试集占总样本的30%
print('X_train = {0}, X_test = {1}, y_train = {2}, y_test ={3}'.format(len(X_train), len(X_test), len(y_train), len(y_test)))
#数据归一化
X_train = MinMaxScaler().fit_transform(X_train)
y_train = MinMaxScaler().fit_transform(y_train)
X_test = MinMaxScaler().fit_transform(X_test)
y_test = MinMaxScaler().fit_transform(y_test)
#Network Parameters
n_hidden = 20 #隐层节点数为30个
n = 3 #特征数
m = len(X_train)
#Hyperparameters
batch = 20
eta = 0.01 #学习率 
max_epoch = 100 #最大训练次数
#采用keras定义一个单隐层的多层感知器模型
model = Sequential()
#model.add(Dense(n_hidden,input_dim = 3, activation='relu')) #Dense 是指密集连接的神经网络的全连接层
model.add(Dense(n_hidden,input_dim = 3,activation='relu')) #Dense 是指密集连接的神经网络的全连接层
model.add(Dense(n_hidden, input_dim=3, activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.summary()
#summary the model
#compile the model
model.compile(loss='mean_squared_error', optimizer='adam')
#fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test),
epochs = max_epoch, batch_size=batch, verbose=1)
#predict the values and calculate RMSE and R2 score
y_test_pred = model.predict(X_test)
y_train_pred= model.predict(X_train)
r2 = r2_score(y_test, y_test_pred)
rmse = mean_squared_error(y_test, y_test_pred)
print('Performance Metric R2:', r2)
plt.scatter(y_test,y_test_pred)
plt.xlabel('y_test')
plt.ylabel('y_test_pred')
plt.show()

keras实现函数拟合-Boston房价的预测_第1张图片 

 

 

 

其实,用keras建立神经网络是非常方便的,想要增加一个隐层,只需要add一下就可以了

model.add(Dense(n_hidden,input_dim = 3,activation='relu')) #Dense 是指密集连接的神经网络的全连接层
model.add(Dense(n_hidden, input_dim=3, activation='relu'))
model.add(Dense(1,activation='sigmoid'))

而且网络的训练也非常的简单,有点像sklearn,只需要model.fit就可以了。

model.fit(X_train, y_train, validation_data=(X_test, y_test),
epochs = max_epoch, batch_size=batch, verbose=1)

测试它的性能,仅仅一行代码便可实现:

y_test_pred = model.predict(X_test)

简单粗暴,傻瓜化

唯一的缺点,在我看来就是导入的包太多了,而且同一种操作可以通过不同的包中的不同的函数去实现,不熟悉的人容易眼花缭乱。

你可能感兴趣的:(Tensorflow深度学习,sklearn,python,神经网络)