机器学习-回归算法




四,代码

# -*- coding: utf-8 -*-
import os
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

num_points = 100

Sample_X = []
Sample_y = []

for i in range(num_points):
    # np.random.normal(mean,divation)
    x1 = np.random.normal(0.0, 0.55)
    x2 = np.random.normal(0.0, 0.56)
    y1 = x1 * 0.1 + x2 * 0.2 + 0.3 + np.random.normal(0.0, 0.03)
    Sample_X.append([x1, x2])
    Sample_y.append([y1])

x_data = Sample_X
y_data = Sample_y


W = tf.Variable(tf.random_uniform([2, 1], -1, 1, dtype=tf.float32), name="weight")
b = tf.Variable(tf.zeros([1, 1]), name="b", dtype=tf.float32)

x_ = tf.placeholder(tf.float32, [100, 2], name="x-input")
y_ = tf.placeholder(tf.float32, [100, 1], name="y-input")

y = tf.add(tf.matmul(x_, W), b)
loss = tf.reduce_mean(tf.square(y-y_), name="loss")

train = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)
init = tf.global_variables_initializer()
count = 0
with tf.Session() as sess:
    sess.run(init)
    for times in range(100000):
        _ = sess.run([train], feed_dict={x_:x_data, y_:y_data})
        loss_ = sess.run([loss], feed_dict={x_:x_data, y_:y_data})
        if count % 100 == 0:
            print(sess.run(W), sess.run(b))
        count = count + 1



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页