Use tensorflow and opencv to achieve visual two classification

The experiment uses two-dimensional coordinate points as data samples

And suppose that the data satisfies the decision line of y=3x-300, that is, the left side of the line is a class, and the right side is a class.

Randomly generate a small number of training samples, use tensorflow to learn the two-layer neural network, and then test after obtaining the model.

import tensorflow as tf
import cv2 as cv
import numpy as np
import random

if __name__ == '__main__':

    train_img = np.ones((300,300,3),np.uint8) * 255
    test_img = np.ones((300,300,3),np.uint8) * 255

    #我们规定的分界函数为y=3x-300

    cv.line(train_img,(200,300),(100,0),(0,255,0))
    cv.line(test_img,(200,300),(100,0),(0,255,0))

    #随机生成训练样本
    data=[]
    label=[]
    for i in range(100):
        x = random.uniform(0,300)
        y = random.uniform(0,300)
        data.append([x,y])

        if 3*x-y-300>0:
            label.append([1])
            cv.line(train_img,(int(x),int(y)),(int(x),int(y)),(0,0,255),2)
        elif 3*x-y-300<0:
            label.append([0])
            cv.line(train_img,(int(x),int(y)),(int(x),int(y)),(255,0,0),2)
        else:
            continue
    
    #网络数据输入
    data_input = tf.placeholder(tf.float32, shape=(None,2))
    label_input = tf.placeholder(tf.float32, shape=(None,1))

    #网络参数初始化
    w1 = tf.Variable(tf.random_normal([2,3]))
    w2 = tf.Variable(tf.random_normal([3,1]))

    #网络架构
    fc1_output = tf.matmul(data_input,w1)
    fc2_output = tf.matmul(fc1_output,w2)

    #反向传播
    loss = tf.reduce_mean(tf.square(label_input-fc2_output))
    train_step = tf.train.GradientDescentOptimizer(0.0000005).minimize(loss)

    model_w1=[]
    model_w2=[]
    with tf.Session() as sess:
        init_op = tf.global_variables_initializer()
        sess.run(init_op)

        BATCH_SIZE = 8
        STEPS = 3000
        for i in range(STEPS):
            start = (i*BATCH_SIZE) % 32
            end = start + BATCH_SIZE
            sess.run(train_step, feed_dict={data_input:data[start:end],label_input:label[start:end]})
            if i%100==0:
                total_loss=sess.run(loss,feed_dict={data_input:data,label_input:label})
                print('after %d training steps, loss on all data is %g' % (i,total_loss))

        #获取训练模型
        model_w1 = sess.run(w1);
        model_w2 = sess.run(w2);

    #测试模型
    for i in range(10000):
        x = random.uniform(0,300)
        y = random.uniform(0,300)

        c=np.dot([[x,y]],model_w1)
        d=np.dot(c,model_w2)

        if d>0.5:
            cv.line(test_img,(int(x),int(y)),(int(x),int(y)),(0,0,255),2)
        else:
            cv.line(test_img,(int(x),int(y)),(int(x),int(y)),(255,0,0),2)


    cv.imshow('train',train_img)
    cv.imshow('test',test_img)
    cv.waitKey(0)

Experimental effect:

         

Guess you like

Origin blog.csdn.net/XLcaoyi/article/details/90753776