import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
import tensorflow as tf
from sklearn.preprocessing import StandardScaler
boston = datasets.load_boston()
X = boston.data[:,5:6]
y = boston.target.reshape(-1,1)
#归一化
standardScaler = StandardScaler()
standardScaler.fit(X)
X = standardScaler.transform(X)
# X = X[y < 50.0]
# y = y[y < 50.0]
print(X.shape)
# plt.scatter(X,y)
# plt.show()
batch_size = 15
#l0 层
#l0 (20,1)
#wo (1,10)
l0 = tf.placeholder(dtype=tf.float32,shape=(None,1),name="l0")
w0 = tf.Variable(tf.random_uniform([1,10],-1.0,1.0))
b0 = tf.Variable(tf.zeros([1,10]))
l1 = tf.matmul(l0,w0) + b0
l1 = tf.nn.relu(l1) # (20,10)
#l1 层
w1 = tf.Variable(tf.random_uniform([10,5],-1.0,1.0),name="l1")
b1 = tf.Variable(tf.zeros([1,5]))
l2 = tf.matmul(l1,w1) + b1
l2 = tf.nn.relu(l2) # (20,5)
#l2 层
w2 = tf.Variable(tf.random_uniform([5,1],-1.0,1.0),name="l2")
b2 = tf.Variable(tf.zeros([1,1]))
y_hat = tf.matmul(l2,w2) + b2 # (20,1)
#损失函数
y_true = tf.placeholder(dtype=tf.float32,shape=(None,1),name="y_true")
loss = tf.reduce_mean(tf.square(y_hat - y_true))
#优化器
optimizer = tf.train.GradientDescentOptimizer(0.0001)
train = optimizer.minimize(loss)
with tf.Session() as sess:
#初始化全局变量
init = tf.global_variables_initializer()
sess.run(init)
for i in range(5000):
start = np.random.randint(0,len(X) - batch_size)
end = start + batch_size
x_train = X[start:end,:]
y_train = y[start:end,:]
result = sess.run([train,loss],feed_dict={l0:x_train,y_true:y_train}) #run 目标
print(result)
#预测一些点,范围(0-9)
X_test = np.linspace(2,9,300).reshape(-1,1)
X_test = standardScaler.transform(X_test) #归一化测试集
y_predict = sess.run(y_hat,feed_dict={l0:X_test})
plt.scatter(X,y)
plt.plot(X_test,y_predict)
plt.show()
神经网络+波士顿房价数据集
最新推荐文章于 2025-02-12 13:15:09 发布