我如何在Tensorflow上修复此代码感知器?

时间:2019-08-06 06:20:56

标签: python-3.x tensorflow machine-learning perceptron

输入:100个2D点被目标2 * x1-3 * x2 + 1 = 0随机分配,Y是标签集。输出:一行可以分隔所有点。我在此源中使用tensorflow。但这并没有给我预期的结果。而且我不知道为什么我错了。

import tensorflow as tf
import numpy as np
import sklearn as skl
import scipy as sci
import pandas as pd
import seaborn as sb
import matplotlib as mplt
import matplotlib.pyplot as plt
import time
np.random.seed(int(time.time())%100);
def fun(x):
    return 2*x[:,0] - 3*x[:,1] + 1;
def generate_data(N):
    X_train = np.random.uniform(-10.0, 10.0 , size = (N, 2));
    Y_train = np.sign(fun(X_train));
    return X_train, Y_train;

N = 100
X_train, Y_train = generate_data(N)

W = tf.Variable(tf.zeros([2,1]));
b = tf.Variable([-1], dtype=tf.float32);

x = tf.compat.v1.placeholder(tf.float32, [N, 2]);
y = tf.compat.v1.placeholder(tf.float32);

model = tf.matmul(x,W) + b;

#   |sign(model) - y|/2
loss_value = tf.reduce_sum(tf.abs(tf.sign(model)-y)/2);

gra_op = tf.compat.v1.train.GradientDescentOptimizer(0.01);

train = gra_op.minimize(loss_value);

init = tf.compat.v1.global_variables_initializer();

sess = tf.compat.v1.Session();
sess.run(init);

for i in range(1000):
    sess.run(train, {x: X_train, y: Y_train});

cW, cb, c_loss = sess.run([W, b, loss_value], {x: X_train, y: Y_train});

print("W: %s %s, b: %s, loss: %s"%(cW[0], cW[1], cb, c_loss));

0 个答案:

没有答案