Logistic regression at the bottom of python

Reference link: Logic gate in Python

Python underlying logic algorithm: Regression: Regression is an important concept of statistics, and its original intention is to predict an accurate output value based on previous data. Logistic regression is the third algorithm in the course "Machine Learning". It is currently the most widely used learning algorithm for solving classification problems. Like the linear regression algorithm, it is also a supervised learning algorithm. Such as: news classification, gene sequence, market division, etc. are divided according to characteristics, using logistic regression. The final prediction results output are: positive class (1), negative class (0).

The logistic regression model is an "S" shaped function:

Cost function: cost function-sum of squares of errors-non-convex function-local minimum point. Gradient descent

import numpy as np

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']

plt.rcParams['axes.unicode_minus']=False

train_data=np.loadtxt(r'LoR_linear.txt',delimiter=',')

test_data=np.loadtxt(r'LoR_nonlinear.txt',delimiter=',')

train_X,train_y=train_data[:,:-1],train_data[:,-1]

test_X,test_y=test_data[:,:-1],test_data[:,-1]

def preProess(X,y):

#Feature zoom

X -=np.mean(X,axis=0)

X /=np.std(X,axis=0,ddof=1)

X=np.c_[np.ones(len(X)),X]

y=np.c_[y]

return X,y

train_X,train_y=preProess(train_X,train_y)

test_X,test_y=preProess(test_X,test_y)

def g(x):

return 1/(1+np.exp(-x))

x=np.linspace(-10,10,500)

y=g(x)

plt.plot(x,y)

plt.show()

def model(X,theta):

z=np.dot(X,theta)

h=g(z)

return h

def costFunc(h,y):

m=len(y)

J=-(1.0/m)np.sum(ynp.log(h)+(1-y)*np.log(1-h))

return J

def gradDesc(X,y,max_iter=15000,alpha=0.1):

m,n=X.shape

theta=np.zeros((n,1))

J_history=np.zeros(max_iter)

for i in range(max_iter):

h=model(X,theta)

J_history[i]=costFunc(h,y)

deltaTheta = (1.0/m)*np.dot(X.T,h-y)

theta -= deltaTheta*alpha

return J_history,theta

def score(h,y):

m=len(y)

count=0

for i in range(m):

h[i]=np.where(h[i]>=0.5,1,0)

if h[i]==y[i]:

count+=1

return count/m

The prediction result function, the result is either 0 or 1

def predict(h):

y_pre=[1 if i>=0.5 else 0 for i in h]

return y_pre

print(train_X.shape,train_y.shape)

J_history,theta=gradDesc(train_X,train_y)

print(theta)

plt.title("cost function")

plt.plot(J_history)

plt.show()

train_h=model(train_X,theta)

test_h=model(test_X,theta)

print(train_h,test_h)

def showDivide(X,theta,y,title):

plt.title(title)

plt.scatter(X[y[:,0]==0,1],X[y[:,0]==0,2],label="negative sample")

plt.scatter(X[y[:,0]==1,1],X[y[:,0]==1,2],label="positive sample")

min_x1,max_x1=np.min(X),np.max(X)

min_x2,max_x2=-(theta[0]+theta[1]*min_x1)/theta[2],-(theta[0]+theta[1]*max_x1)/theta[2]

plt.plot([min_x1,max_x1],[min_x2,max_x2])

plt.legend()

plt.show()

showDivide(train_X,theta,train_y,'training set')

showDivide(test_X,theta,test_y,'test set set')

train_y1=predict(train_h)

print('The predicted result is:',train_y1)

Recommended Posts

Logistic regression at the bottom of python
How about learning python at the age of 27?
Consolidate the foundation of Python (4)
Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
Python Data Science: Logistic Regression
Consolidate the foundation of Python(5)
Consolidate the foundation of Python (3)
Python handles the 4 wheels of Chinese
Python simulation of the landlord deal
What is the use of Python
The premise of Python string pooling
Secrets of the new features of Python 3.8
The father of Python joins Microsoft
The operation of python access hdfs
The usage of tuples in python
End the method of running python
Understanding the meaning of rb in python
Can Python implement the structure of the stack?
Learn the basics of python interactive mode
What are the required parameters of python
The usage of Ajax in Python3 crawler
Python solves the Tower of Hanoi game
Solve the conflict of multiple versions of python
What is the scope of python variables
Python implements the sum of fractional sequences
Two days of learning the basics of Python
What is the id function of python
Where is the pip path of python3
The essence of Python language: Itertools library
What are the advantages of python language
The specific method of python instantiation object
python3 realizes the function of mask drawing
What is the prospect of python development
What is the function body of python
The specific method of python import library
Solve the conflict of multiple versions of python
What is the function of adb in python
Detailed explanation of the principle of Python super() method
The difference between the syntax of java and python
7 features of Python3.9
Python realizes the development of student management system
Python implements the shuffling of the cards in Doudizhu
The meaning and usage of lists in python
Solve the problem of python running startup error
Can the value of the python dictionary be modified?
Python implements the source code of the snake game
First look at the new features of Ubuntu 17.10
Detailed explanation of the usage of Python decimal module
2.1 The Python Interpreter (python interpreter)
The consequences of uninstalling python in ubuntu, very
Python writes the game implementation of fishing master
[898] python get the intersection of two lists | union | difference
What is the advantage of python over corporate language
A brief summary of the difference between Python2 and Python3
Solve the problem of python compiling and installing ssl
Detailed explanation of the implementation steps of Python interface development
How does python call the key of a dictionary
Python crawls the full set of skins of the king pesticide
How to understand the introduction of packages in Python
Solve the problem of convex hull based on python