import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
df = pd.read_csv('data/boston.csv', header=0)
df = df.values
df = np.array(df)
for i in range(12):
df[:, i] = df[:, i]/(df[:, i].max()-df[:, i].min())
x_data = df[:, :12]
y_data = df[:, 12]
x = tf.placeholder(tf.float32, [None, 12], name='X')
y = tf.placeholder(tf.float32, [None, 1], name='Y')
with tf.name_scope('Model'):
w = tf.Variable(tf.random_normal([12, 1], stddev=0.01), name='w')
b = tf.Variable(1.0, name='b')
def model(x, w, b):
wx_b = tf.matmul(x, w) + b
return wx_b
L2 = model(x, w, b)
train_epochs = 50
learning_rate = 0.01
with tf.name_scope('Loss'):
loss = tf.reduce_mean(tf.square(y-L2))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
loss_list = []
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for epoch in range(train_epochs):
loss_sum = 0.0
for xs, ys in zip(x_data, y_data):
xs = xs.reshape(1, 12)
ys = ys.reshape(1, 1)
_, loss_f = sess.run([optimizer, loss], feed_dict={x:xs, y:ys})
loss_sum = loss_sum + loss_f
xvalue, yvalue = shuffle(x_data, y_data)
b0temp = b.eval(session=sess)
w0temp = w.eval(session=sess)
loss_average = loss_sum/len(y_data)
loss_list.append(loss_average)
plt.plot(loss_list)
n = np.random.randint(506)
print(n)
x_test = x_data[n]
x_test = x_test.reshape(1, 12)
predict = sess.run(L2, feed_dict={x: x_test})
print('预测值 %f' % predict)
target = y_data[n]
print('标签值 %f' % target)