Pure code for fitting linear regression via neural networks
Refer to the article in the link, there was an error and I corrected it.
And the original article is required dataset file, I give directly replaced with an array, using direct assignment.
# -*- coding: utf-8 -*- import numpy as np import as plt class SimpleDataReader(object): def __init__(self, data_file): self.train_file_name = data_file self.num_train = 0 = None = None # read data from file def ReadData(self): # data = (self.train_file_name) # = data["data"] # = data["label"] = ([0.95, 3, 4, 5.07, 6.03, 8.21, 8.85, 12.02, 15], dtype=float) = ([5.1, 8.7, 11.5, 13, 15.3, 18, 21, 26.87, 32.5], dtype=float) self.num_train = [0] #end if # get batch training data def GetSingleTrainSample(self, iteration): x = [iteration] y = [iteration] return x, y def GetWholeTrainSamples(self): return , class NeuralNet(object): def __init__(self, eta): = eta = 0 = 0 def __forward(self, x): z = x * + return z def __backward(self, x,y,z): dz = z - y # The original error was: dz = x * (z - y) db = dz dw = dz return dw, db def __update(self, dw, db): = - * dw = - * db def train(self, dataReader): for i in range(dataReader.num_train): # get x and y value for one sample x,y = (i) # get z from x,y z = self.__forward(x) # calculate gradient of w and b dw, db = self.__backward(x, y, z) # update w,b self.__update(dw, db) # end for def inference(self, x): return self.__forward(x) if __name__ == '__main__': # read data sdr = SimpleDataReader('') () # create net eta = 0.1 net = NeuralNet(eta) (sdr) # result print("w=%f,b=%f" %(, )) # Plotting section trainX,trainY = () fig = () ax = fig.add_subplot(111) # Scatterplotting (trainX,trainY) # Plotting linear regression x = (0, 15, 0.01) f = (, excluded=['x']) (x,f(x),color='red') # Show charts ()
Ref:
Fitting of linear regression through neural networks
Python Prediction Using Linear Regression and Neural Network Models
Road traffic consists mainly of both road passenger traffic and road freight traffic.
According to the study, the highway capacity of an area is mainly related to the number of people in the area, the number of motor vehicles, and the size of the highway, and the data related to the highway capacity of a particular area for a period of 20 years are given in Table 5-11.
According to data from the relevant authorities, the number of people in the region in 2010 and 2011 was 733,900 and 755,500, the number of motor vehicles was 39,635 and 40,975, and the area of roads was 98,800 square kilometers and 10,268 square kilometers, respectively.
Use a BP neural network to predict the amount of highway passenger traffic and the amount of highway freight traffic in the region for the years 2010 and 2011.
Table 5-11 Capacity Data Table
Year Number of people Number of motor vehicles Road area Kilometers of passenger traffic Kilometers of freight traffic
1990 20.55 0.6 0.09 5126 1237
1991 22.44 0.75 0.11 6217 1379
1992 25.37 0.85 0.11 7730 1385
1993 27.13 0.9 0.14 9145 1399
1994 29.45 1.05 0.2 10460 1663
1995 30.1 1.35 0.23 11387 1714
1996 30.96 1.45 0.23 12353 1834
1997 34.06 1.6 0.32 15750 4322
1998 36.42 1.7 0.32 18304 8132
1999 38.09 1.85 0.34 19836 8936
2000 39.13 2.15 0.36 21024 11099
2001 39.99 2.2 0.36 19490 11203
2002 41.93 2.25 0.38 20433 10524
2003 44.59 2.35 0.49 22598 11115
2004 47.3 2.5 0.56 25107 13320
2005 52.89 2.6 0.59 33442 16762
2006 55.73 2.7 0.59 36836 18673
2007 56.76 2.85 0.67 40548 20724
2008 59.17 2.95 0.69 42927 20803
2009 60.63 3.1 0.79 43462 21804
Note: Data taken from Matlab in Mathematical Modeling (2nd Edition), Jinwu Zhuo, p. 134.
#1. Data acquisition import pandas as pd data = pd.read_excel('Capacity Data Sheet.xlsx') x = [:20,:4] y = [:20,4:] #2. Introducing the linear regression module, referred to as LR. from sklearn.linear_model import LinearRegression as LR lr = LR() # Create linear regression model classes (x,y) #fitting slr=(x,y) #Coefficient of determination R^2 c_x=lr.coef_ Regression coefficients corresponding to #x c_b=lr.intercept_ # Regression coefficient constant term #3. Projections x1 = [20:,:4] r1=(x1) # Use self-contained function prediction #print('The x regression coefficient is:',c_x) #print('The constant term of the regression coefficient is:',c_b) #print('The coefficient of determination is:',slr) #print('The sample predicted value is:',r1) n=list(data["Kilometers of passenger traffic (10,000)"]) (r1[:,0]) num=(n).dropna() g=list(data["Kilometers of freight (tons)"]) (r1[:,1]) gravity=(g).dropna() import pandas as pd import as plt # Import the pyplot module from the plotting library, and call it plt for short. # Construct the horizontal and vertical axis data columns required for plotting. # Plotting linear graphs on the figure interface ['-serif'] = 'SimHei' #Set the font to SimHei (1) (data["Year"],num,'r*--') #Red "*" continuous chart. ('Date') ('Kilometers of passenger traffic (10,000)') ('Kilometer Passenger Traffic (10,000) Trend') (data["Year"],rotation = 45) ('myfigure1') (2) (data["Year"],gravity,'b*--') #Red "*" continuous chart. ('Date') ('Kilometers of freight (tons)') ('Kilometer freight volume (tons) trend') (data["Year"],rotation = 45) ('myfigure2') from sklearn.neural_network import MLPRegressor clf = MLPRegressor(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=8, random_state=1) (x, y); rv=(x,y) r2=(x1) print('The sample predicted values are:',r2) n2=list(data["Kilometers of passenger traffic (10,000)"]) (r2[:,0]) num2=(n2).dropna() g2=list(data["Kilometers of freight (tons)"]) (r2[:,1]) gravity2=(g2).dropna()
The results show:
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.