本文实例为大家分享了TensorFlow实现Logistic回归的具体代码,供大家参考,具体内容如下
1.导入模块
import numpy as np import pandas as pd from pandas import Series,DataFrame from matplotlib import pyplot as plt %matplotlib inline #导入tensorflow import tensorflow as tf #导入MNIST(手写数字数据集) from tensorflow.examples.tutorials.mnist import input_data
2.获取训练数据和测试数据
import ssl ssl._create_default_https_context = ssl._create_unverified_context mnist = input_data.read_data_sets('./TensorFlow',one_hot=True) test = mnist.test test_images = test.images train = mnist.train images = train.images
3.模拟线性方程
#创建占矩阵位符X,Y X = tf.placeholder(tf.float32,shape=[None,784]) Y = tf.placeholder(tf.float32,shape=[None,10]) #随机生成斜率W和截距b W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) #根据模拟线性方程得出预测值 y_pre = tf.matmul(X,W)+b #将预测值结果概率化 y_pre_r = tf.nn.softmax(y_pre)
4.构造损失函数
# -y*tf.log(y_pre_r) --->-Pi*log(Pi) 信息熵公式 cost = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(y_pre_r),axis=1))
5.实现梯度下降,获取最小损失函数
#learning_rate:学习率,是进行训练时在最陡的梯度方向上所采取的「步」长; learning_rate = 0.01 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
6.TensorFlow初始化,并进行训练
#定义相关参数 #训练循环次数 training_epochs = 25 #batch 一批,每次训练给算法10个数据 batch_size = 10 #每隔5次,打印输出运算的结果 display_step = 5 #预定义初始化 init = tf.global_variables_initializer() #开始训练 with tf.Session() as sess: #初始化 sess.run(init) #循环训练次数 for epoch in range(training_epochs): avg_cost = 0. #总训练批次total_batch =训练总样本量/每批次样本数量 total_batch = int(train.num_examples/batch_size) for i in range(total_batch): #每次取出100个数据作为训练数据 batch_xs,batch_ys = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer,cost],feed_dict={X:batch_xs,Y:batch_ys}) avg_cost +=c/total_batch if(epoch+1)%display_step == 0: print(batch_xs.shape,batch_ys.shape) print('epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost)) print('Optimization Finished!') #7.评估效果 # Test model correct_prediction = tf.equal(tf.argmax(y_pre_r,1),tf.argmax(Y,1)) # Calculate accuracy for 3000 examples # tf.cast类型转换 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) print("Accuracy:",accuracy.eval({X: mnist.test.images[:3000], Y: mnist.test.labels[:3000]}))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]