1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import pandas as pd # 用于读取数据文件 import tensorflow as tf import matplotlib.pyplot as plt # 用于画图 import numpy as np
df = pd.read_csv("input.csv", header=None) train_data = df.values
print(train_data)
train_X = train_data[:, :-1] train_y = train_data[:, -1:] feature_num = len(train_X[0]) sample_num = len(train_X) print("Size of train_X: {}x{}".format(sample_num, feature_num)) print("Size of train_y: {}x{}".format(len(train_y), len(train_y[0])))
X = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32)
W = tf.Variable(tf.zeros([feature_num, 1])) b = tf.Variable([-.9])
db = tf.matmul(X, tf.reshape(W, [-1, 1])) + b hyp = tf.sigmoid(db)
cost0 = y * tf.log(hyp) cost1 = (1 - y) * tf.log(1 - hyp) cost = (cost0 + cost1) / -sample_num loss = tf.reduce_sum(cost)
optimizer = tf.train.GradientDescentOptimizer(0.001) train = optimizer.minimize(loss)
init = tf.global_variables_initializer() sess = tf.Session() sess.run(init)
feed_dict = {X: train_X, y: train_y}
for step in range(1000000): sess.run(train, {X: train_X, y: train_y}) if step % 10000 == 0: print(step, sess.run(W).flatten(), sess.run(b).flatten())
# 绘图
w = [0.7672361 , -0.276697 , -0.19542742] b = 0.09650069
from mpl_toolkits.mplot3d import Axes3D
x1 = train_data[:, 0] x2 = train_data[:, 1] x3 = train_data[:, 2] y = train_data[:, -1:]
fig=plt.figure() ax=Axes3D(fig)
for x1p, x2p, x3p, yp in zip(x1, x2, x3, y): if yp == 0: ax.scatter(x1p, x2p, x3p, c='r') else: ax.scatter(x1p, x2p, x3p, c='g')
ax.set_zlabel('Z') # 坐标轴 ax.set_ylabel('Y') ax.set_xlabel('X')
a = 0.7672361 b = -0.276697 c = -0.19542742 d = 0.09650069
x1 = np.linspace(-1,1,10) y1 = np.linspace(-1,1,10)
X,Y = np.meshgrid(x1,y1) Z = (d - a*X - b*Y) / c
fig = plt.figure() ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z)
|