首页 > 其他分享 >tensorflow 实现Logistic Regression

tensorflow 实现Logistic Regression

时间:2022-11-01 18:04:11浏览次数:49  
标签:target vals train Logistic tf tensorflow data Regression predictors


import lib

import numpy as np
import tensorflow as tf
from sklearn import datasets
import pandas as pd
from sklearn.cross_validation import train_test_split
from matplotlib import pyplot

load data and split the data

# 1. Loading Data
iris = datasets.load_iris()
# Predictors Two columns : Sepal Length and Sepal Width
predictors_vals = np.array([predictor[0:2] for predictor in iris.data])
# For setosa Species, target is 0.
target_vals = np.array([1. if predictor==0 else 0. for predictor in iris.target])


# 2. Split data into train/test = 75%/25%
predictors_vals_train, predictors_vals_test, target_vals_train, target_vals_test = train_test_split(predictors_vals, target_vals,
train_size=0.75,
random_state=0)

create variables

# 3. Normalize if needed


#4.Initialize placeholders that will contain predictors and target
x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

#5. Create variables (Weight and Bias) that will be tuned up
W = tf.Variable(tf.ones(shape=[2,1]))
b = tf.Variable(tf.ones(shape=[1,1]))

make model

# 6. Declare model operations : y = xW +b 
model = tf.add(tf.matmul(x_data, W), b)

#7. Declare loss function and Optimizer
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model, labels=y_target))
my_opt = tf.train.AdamOptimizer(0.02) #learning rate =0.02
train_step = my_opt.minimize(loss)

#8. Initialize variables and session
init = tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)

#9. Actual Prediction:
prediction = tf.round(tf.sigmoid(model))
predictions_correct = tf.cast(tf.equal(prediction, y_target), tf.float32)
accuracy = tf.reduce_mean(predictions_correct)

train

#10. Training loop
lossArray = []
trainAccuracy = []
testAccuracy = []
for i in range(1000):
#Random instances for Batch size
batch_size = 4 #Declare batch size
batchIndex = np.random.choice(len(predictors_vals_train), size=batch_size)
batchX = predictors_vals_train[batchIndex]
batchY = np.transpose([target_vals_train[batchIndex]])
# Tuning weight and bias while minimizing loss function through optimizer
sess.run(train_step, feed_dict={x_data: batchX, y_target: batchY})
#loss function per epoch/generation
batchLoss = sess.run(loss, feed_dict={x_data: batchX, y_target: batchY})
lossArray.append(batchLoss) # adding it to loss_vec
# accuracy for each epoch for train
batchAccuracyTrain = sess.run(accuracy, feed_dict={x_data: predictors_vals_train, y_target: np.transpose([target_vals_train])})
trainAccuracy.append(batchAccuracyTrain) # adding it to train_acc
# accuracy for each epoch for test
batchAccuracyTest = sess.run(accuracy, feed_dict={x_data: predictors_vals_test, y_target: np.transpose([target_vals_test])})
testAccuracy.append(batchAccuracyTest)
# printing loss after 10 epochs/generations to avoid verbosity
if (i+1)%50==0:
print('Loss = ' + str(batchLoss)+ ' and Accuracy = ' + str(batchAccuracyTrain))

eval

# 11. Check model performance
pyplot.plot(lossArray, 'r-' )
pyplot.title('Logistic Regression: Cross Entropy Loss per Epoch')
pyplot.xlabel('Epoch')
pyplot.ylabel('Cross Entropy Loss')
pyplot.show()

tensorflow 实现Logistic Regression_python


标签:target,vals,train,Logistic,tf,tensorflow,data,Regression,predictors
From: https://blog.51cto.com/u_13859040/5814621

相关文章

  • 机器学习从入门到精通—— Logistic回归与最大熵模型
    Logistic回归​​Logistic回归​​​​逻辑斯谛​​​​回归模型​​​​相对应模型代码实现​​​​逻辑斯蒂​​​​最大熵模型代码实现​​Logistic回归逻辑斯谛1.逻辑斯......
  • 机器学习 之 逻辑回归(LogisticRegression)文本算法的精确率
    目录​​0、推荐​​​​1、背景​​​​2、效果图​​​​3、本次实验整体流程​​​​4、这里用词向量,而不是TF-IDF预处理后的向量​​​​5、源代码​​​​6、知识点普......
  • tensorflow2中以复制方式扩展tensor —— tf.tile()
    tensorflow2.0环境下,以复制方式扩展tensor,可以使用​​tf.tile()​​函数。该函数定义如下(图自官网):https://www.tensorflow.org/api_docs/python/tf/keras/backend/tiletf......
  • 2、tensorflow
    1、已经安装了scipy,但是无法调用'ImagetransformationsrequireSciPy.'、'InstallSciPy.'name'scipy'isnotdefined解决方法:pip3-Vpython3-mscipypytho......
  • 安装TensorFlow CPU版本
    TensorFlow1.1TensorFlow介绍  TensorFlow就是谷歌公司推出的一款高效的人工智能开源框架,自从2015年11月发布以来,已经成为全世界最广泛使用的深度学习库。很多以前难......
  • TensorFlow.NET机器学习入门【0】前言与目录
    TensorFlow.NET机器学习入门【0】前言与目录    曾经学习过一段时间ML.NET的知识,ML.NET是微软提供的一套机器学习框架,相对于其他的一些机器学习框架,ML.NET侧重于......
  • 【解决错误】AttributeError: module 'tensorflow.compat.v2.__internal__' has no at
    原因一般为tensorflow和keras版本不匹配。解决方法以下是tensorflow版本对应关系我最开始使用的为tensorflow=2.4.0,keras=2.4.3,但是问题仍然没有解决,我就安装了te......
  • 线性回归 Linear Regression
    线性回归的预设线性只能通过每个样本各维的线性组合获得预测结果,这使得函数很简单,但拟合能力较弱。同方差性每个样本的方差不变。方差不同会使得拟合函数对某些数......
  • anaconda 下安装tensorflow & keras
    首先,同胞们要记住,你要做什么?该怎么做?你的目标是什么?千万不要因为中间遇到的连带问题,而忘记了你要做什么?一下开始介绍:????下载:官网速度很慢,容易断线:https://www.......
  • tensorflow:OOM when allocating tensor with shape[225,256,256,36] and type float
    运行TensorFlow(GPU)报错如下:OOMwhenallocatingtensorwithshape[225,256,256,36]andtypefloaton/job:localhost/replica:0/tas原因是GPUOOM内存不够,因此可尝试改成......