import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
import tensorflow as tf
sess=tf.Session()
iris=datasets.load_iris()
# print(iris.target)
# print(iris.keys,iris.values,iris.items)
# python获取对象成员信息 :dir(obj)
# print(dir(iris))
# ['DESCR', 'data', 'feature_names', 'filename', 'target', 'target_names']
# 根据class目标是否为山鸢尾将其转换成1或者0,iris数据集将山鸢尾标记为0,将其从0置为1,同时将其它物种标记为0
# 训练只使用花瓣长度与花瓣宽度,这两个特征在第三列和第四列
binary_target=np.array([1. if x==0 else 0. for x in iris.target])
# print(binary_target)
iris_2d=np.array([[x[2],x[3]] for x in iris.data])
# print(iris_2d.size)
# 各150组数据,共300,150*2
# print(type(iris_2d))<class 'numpy.ndarray'>
# print(iris_2d.shape) (150, 2)
# 声明批量训练大小、占位符及模型变量
batch_size=200
x1_data=tf.placeholder(shape=[None,1],dtype=tf.float32)
x2_data=tf.placeholder(shape=[None,1],dtype=tf.float32)
y_target=tf.placeholder(shape=[None,1],dtype=tf.float32)
A=tf.Variable(tf.random_normal(shape=[1,1]))
b=tf.Variable(tf.random_normal(shape=[1,1]))
# 定义线性模型 线性模型为:x2=x1*A+b,将公式x2-x1*A-b传入sigmoid函数,预测结果1或者0
my_mult=tf.matmul(x1_data,A)
my_add=tf.add(my_mult,b)
my_output=tf.subtract(x2_data,my_add)
# 使用sigmoid交叉熵损失函数sigmoid_cross_entropy_with_logits()
xentropy=tf.nn.sigmoid_cross_entropy_with_logits(labels = y_target, logits = my_output)
# 使用优化器,最小化交叉熵损失,选择学习率为0.05
my_opt=tf.train.GradientDescentOptimizer(0.05)
train_step=my_opt.minimize(xentropy)
# 初始化变量
init=tf.global_variables_initializer()
sess.run(init)
# 迭代执行1000训练线性模型,传入三种数据:花瓣长度,花瓣宽度,目标变量,每200次迭代打印出变量值
for i in range(1000):
rand_index=np.random.choice(len(iris_2d),size=batch_size)
rand_x=iris_2d[rand_index]
# print(rand_x)
rand_x1=np.array([[x[0]] for x in rand_x])
rand_x2=np.array([[x[1]] for x in rand_x])
rand_y=np.array([[y] for y in binary_target[rand_index]])
sess.run(train_step,feed_dict={x1_data:rand_x1,x2_data:rand_x2,y_target:rand_y})
if(i+1)%200==0:
print('Step # ' +str(i+1) + ' A= ' +str(sess.run(A)) + 'b= ' +str(sess.run(b)))
print('Step # ' +str(i+1) + ' A= ' +str(sess.run(A)[0][0]) + ' b = ' +str(sess.run(b)[0][0]))
# print('\n')
[[slope]]=sess.run(A)
[[intercept]]=sess.run(b)
x=np.linspace(0,3,num=50)
ablineValues=[]
for i in x:
ablineValues.append(slope*i+intercept)
setosa_x=[a[0] for i,a in enumerate(iris_2d) if binary_target[i]==1]
setosa_y=[a[1] for i,a in enumerate(iris_2d) if binary_target[i]==1]
non_setosa_x=[a[0] for i,a in enumerate(iris_2d) if binary_target[i]==0]
non_setosa_y=[a[1] for i,a in enumerate(iris_2d) if binary_target[i]==0]
print(setosa_x)
print(setosa_y)
print(non_setosa_x)
print(non_setosa_y)
plt.plot(setosa_x,setosa_y,'rx',ms=10,mew=2,label='setosa''')
plt.plot(non_setosa_x,non_setosa_y,'ro',label='non-setosa')
plt.plot(x,ablineValues,'b-')
plt.xlim([0.0,7.5])
plt.ylim([0.0,2.6])
plt.suptitle('Linear' ,fontsize=20)
plt.xlabel('Petal Length')
plt.ylabel('Petal Width')
plt.legend(loc='lower right')
plt.show()
TF-cookbook c2创建分类器
最新推荐文章于 2024-09-06 00:00:00 发布