python-tensorflow实现softmax二分类(精度0.71,待改进)

it2025-03-25  7

''' 作业:自己构建一个数据,分类的额数据(特性:特征x1和x2, 5*x1-3*x2>0是第一个类别,5*x1-3*x2<0是第二个类别) 使用softmax相关API实现分类 ''' import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import random '''Tensorflow实现分类任务''' '''先实现二分类''' def binary_classification(): learningRate = 0.005 #构建分类数据 x1 = np.arange(-10,10,0.01).reshape(-1,1) x2 = np.arange(-10,10,0.01).reshape(-1,1) x = np.hstack((x1,x2)) y = 3*x1+2*x2**2 y_label = np.zeros((y.shape[0],2)) y_label[y[:,0]>100,0] = 1 #0 y_label[y[:,0]<=100,1] = 1 #1 #将数据分为2份,一份用于测试,一份用于训练 random.seed(0) data_list = list(range(2000)) train_list = [random.randint(0,1999) for i in range(int(x1.shape[0]*0.8))] #训练数据 train_x = x[train_list,:] train_y = y_label[train_list,:] #测试数据 for i in train_list: if i in data_list: data_list.remove(i) test_list = data_list test_x = x[test_list,:] test_y = y_label[test_list,:] plt.plot(y,y_label,'*') # plt.show() #构建模型 xx = tf.placeholder(dtype=tf.float32,shape=[None,2],name='xx') yy = tf.placeholder(dtype=tf.float32,shape=[None,2],name='yy') layer1_v = tf.Variable(initial_value=tf.random_normal(shape=[2,2],dtype=tf.float32,seed=0),name='layer1') b = tf.Variable(initial_value=tf.random_normal(shape=[2],seed=0),name='b') #加上了bias后精度从0.57提升到了0.71 #softmax进行二分类 predict = tf.nn.softmax(tf.matmul(xx,layer1_v)+b) #损失函数 loss = tf.reduce_sum(-yy*tf.log(predict)) #优化器 Optimizer = tf.train.AdamOptimizer(learning_rate=learningRate).minimize(loss) #accuracy accuracy = tf.equal(tf.argmax(predict,1),tf.argmax(yy,1)) accuracy = tf.reduce_mean(tf.cast(accuracy,dtype=tf.float32)) with tf.Session() as sess: tf.global_variables_initializer().run() step = 0 for i in range(1000): Optimizer.run(feed_dict={xx:train_x,yy:train_y}) print("loss:%f,accuracy:%f"%(loss.eval(feed_dict={xx:train_x,yy:train_y}),accuracy.eval(feed_dict={xx:test_x,yy:test_y}))) binary_classification()

精度测试:

0.71 待改进(或许通过批次送入进行训练会增加模型的精度)

最新回复(0)