import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow.keras
from tensorflow.keras import layers
import os
from sklearn import preprocessing #用于标准化
#开启gpu
os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘0’
features=pd.read_csv(‘housing.csv’)
print(features.head())
print(features.shape)
#标签
labels = np.array(features[‘MEDV’])
features=features.drop(‘MEDV’, axis=1)
#名字单独保存一下,以备后患
features =np.array(features)
#数据进行标准化
input_features=preprocessing.StandardScaler().fit_transform(features)
print(input_features[0])
#新建一个model,一个神经网络
model=tf.keras.Sequential()
model.add(layers.Dense(16))
model.add(layers.Dense(32))
model.add(layers.Dense(1))
#设定模型的学习率和损失函数
model.compile(optimizer=tf.keras.optimizers.SGD(0.001),loss=‘mean_squared_error’)
#设定模型的输入值,x和y,训练的样本,轮数,
model.fit(input_features,labels,validation_split=0.25,epochs=10,batch_size=64)
#model.summary() #查看模型的构成
predict = model.predict(input_features)
plt.figure(figsize=(20,10)) #设置窗口的大小
plt.ylabel(‘Price’)
plt.plot(labels,‘b-’,label=‘true’)
plt.plot(predict,‘ro’,label=‘predict’)
plt.legend()
plt.show()