導航:首頁 > 編程語言 > python回歸結果輸出

python回歸結果輸出

發布時間:2022-11-25 08:10:06

python邏輯回歸結果怎麼看

假設預測目標為0和1 數據中1的個數為a,預測1的次數為b,預測1命中的次數為c 准確率 precision = c / b 召回率 recall = c / a f1_score = 2 * precision * recall / (precision + recall)

㈡ 關於python簡單線性回歸

線性回歸:
設x,y分別為一組數據,代碼如下
import matplotlib.pyplot as plt
import numpy as np
ro=np.polyfit(x,y,deg=1) #deg為擬合的多項式的次數(線性回歸就選1)
ry=np.polyval(ro,x) #忘記x和ro哪個在前哪個在後了。。。
print ro #輸出的第一個數是斜率k,第二個數是縱截距b
plt.scatter(x,y)
plt.plot(x,ry)

㈢ 使用Python的線性回歸問題,怎麼解決

本文中,我們將進行大量的編程——但在這之前,我們先介紹一下我們今天要解決的實例問題。

1) 預測房子價格

閃電俠是一部由劇作家/製片人Greg Berlanti、Andrew Kreisberg和Geoff Johns創作,由CW電視台播放的美國電視連續劇。它基於DC漫畫角色閃電俠(Barry Allen),一個具有超人速度移動能力的裝扮奇特的打擊犯罪的超級英雄,這個角色是由Robert Kanigher、John Broome和Carmine Infantino創作。它是綠箭俠的衍生作品,存在於同一世界。該劇集的試播篇由Berlanti、Kreisberg和Johns寫作,David Nutter執導。該劇集於2014年10月7日在北美首映,成為CW電視台收視率最高的電視節目。

綠箭俠是一部由劇作家/製片人 Greg Berlanti、Marc Guggenheim和Andrew Kreisberg創作的電視連續劇。它基於DC漫畫角色綠箭俠,一個由Mort Weisinger和George Papp創作的裝扮奇特的犯罪打擊戰士。它於2012年10月10日在北美首映,與2012年末開始全球播出。主要拍攝於Vancouver、British Columbia、Canada,該系列講述了億萬花花公子Oliver Queen,由Stephen Amell扮演,被困在敵人的島嶼上五年之後,回到家鄉打擊犯罪和腐敗,成為一名武器是弓箭的神秘義務警員。不像漫畫書中,Queen最初沒有使用化名」綠箭俠「。

由於這兩個節目並列為我最喜愛的電視節目頭銜,我一直想知道哪個節目更受其他人歡迎——誰會最終贏得這場收視率之戰。 所以讓我們寫一個程序來預測哪個電視節目會有更多觀眾。 我們需要一個數據集,給出每一集的觀眾。幸運地,我從維基網路上得到了這個數據,並整理成一個.csv文件。它如下所示。

閃電俠

閃電俠美國觀眾數

綠箭俠

綠箭俠美國觀眾數

1 4.83 1 2.84

2 4.27 2 2.32

3 3.59 3 2.55

4 3.53 4 2.49

5 3.46 5 2.73

6 3.73 6 2.6

7 3.47 7 2.64

8 4.34 8 3.92

9 4.66 9 3.06

觀眾數以百萬為單位。

解決問題的步驟:

首先我們需要把數據轉換為X_parameters和Y_parameters,不過這里我們有兩個X_parameters和Y_parameters。因此,把他們命名為flash_x_parameter、flash_y_parameter、arrow_x_parameter、arrow_y_parameter吧。然後我們需要把數據擬合為兩個不同的線性回歸模型——先是閃電俠,然後是綠箭俠。 接著我們需要預測兩個電視節目下一集的觀眾數量。 然後我們可以比較結果,推測哪個節目會有更多觀眾。

步驟1

導入我們的程序包:

Python

1

2

3

4

5

6

7

# Required Packages

import csv

import sys

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

from sklearn import datasets, linear_model

步驟2

寫一個函數,把我們的數據集作為輸入,返回flash_x_parameter、flash_y_parameter、arrow_x_parameter、arrow_y_parameter values。

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

# Function to get data

def get_data(file_name):

data = pd.read_csv(file_name)

flash_x_parameter = []

flash_y_parameter = []

arrow_x_parameter = []

arrow_y_parameter = []

for x1,y1,x2,y2 in zip(data['flash_episode_number'],data['flash_us_viewers'],data['arrow_episode_number'],data['arrow_us_viewers']):

flash_x_parameter.append([float(x1)])

flash_y_parameter.append(float(y1))

arrow_x_parameter.append([float(x2)])

arrow_y_parameter.append(float(y2))

return flash_x_parameter,flash_y_parameter,arrow_x_parameter,arrow_y_parameter

現在我們有了我們的參數,來寫一個函數,用上面這些參數作為輸入,給出一個輸出,預測哪個節目會有更多觀眾。

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

# Function to know which Tv show will have more viewers

def more_viewers(x1,y1,x2,y2):

regr1 = linear_model.LinearRegression()

regr1.fit(x1, y1)

predicted_value1 = regr1.predict(9)

print predicted_value1

regr2 = linear_model.LinearRegression()

regr2.fit(x2, y2)

predicted_value2 = regr2.predict(9)

#print predicted_value1

#print predicted_value2

if predicted_value1 > predicted_value2:

print "The Flash Tv Show will have more viewers for next week"

else:

print "Arrow Tv Show will have more viewers for next week"

把所有東西寫在一個文件中。打開你的編輯器,把它命名為prediction.py,復制下面的代碼到prediction.py中。

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

# Required Packages

import csv

import sys

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

from sklearn import datasets, linear_model

# Function to get data

def get_data(file_name):

data = pd.read_csv(file_name)

flash_x_parameter = []

flash_y_parameter = []

arrow_x_parameter = []

arrow_y_parameter = []

for x1,y1,x2,y2 in zip(data['flash_episode_number'],data['flash_us_viewers'],data['arrow_episode_number'],data['arrow_us_viewers']):

flash_x_parameter.append([float(x1)])

flash_y_parameter.append(float(y1))

arrow_x_parameter.append([float(x2)])

arrow_y_parameter.append(float(y2))

return flash_x_parameter,flash_y_parameter,arrow_x_parameter,arrow_y_parameter

# Function to know which Tv show will have more viewers

def more_viewers(x1,y1,x2,y2):

regr1 = linear_model.LinearRegression()

regr1.fit(x1, y1)

predicted_value1 = regr1.predict(9)

print predicted_value1

regr2 = linear_model.LinearRegression()

regr2.fit(x2, y2)

predicted_value2 = regr2.predict(9)

#print predicted_value1

#print predicted_value2

if predicted_value1 > predicted_value2:

print "The Flash Tv Show will have more viewers for next week"

else:

print "Arrow Tv Show will have more viewers for next week"

x1,y1,x2,y2 = get_data('input_data.csv')

#print x1,y1,x2,y2

more_viewers(x1,y1,x2,y2)

可能你能猜出哪個節目會有更多觀眾——但運行一下這個程序看看你猜的對不對。

3) 替換數據集中的缺失值

有時候,我們會遇到需要分析包含有缺失值的數據的情況。有些人會把這些缺失值捨去,接著分析;有些人會用最大值、最小值或平均值替換他們。平均值是三者中最好的,但可以用線性回歸來有效地替換那些缺失值。

這種方法差不多像這樣進行。

首先我們找到我們要替換那一列里的缺失值,並找出缺失值依賴於其他列的哪些數據。把缺失值那一列作為Y_parameters,把缺失值更依賴的那些列作為X_parameters,並把這些數據擬合為線性回歸模型。現在就可以用缺失值更依賴的那些列預測缺失的那一列。

一旦這個過程完成了,我們就得到了沒有任何缺失值的數據,供我們自由地分析數據。

為了練習,我會把這個問題留給你,所以請從網上獲取一些缺失值數據,解決這個問題。一旦你完成了請留下你的評論。我很想看看你的結果。

個人小筆記:

我想分享我個人的數據挖掘經歷。記得在我的數據挖掘引論課程上,教師開始很慢,解釋了一些數據挖掘可以應用的領域以及一些基本概念。然後突然地,難度迅速上升。這令我的一些同學感到非常沮喪,被這個課程嚇到,終於扼殺了他們對數據挖掘的興趣。所以我想避免在我的博客文章中這樣做。我想讓事情更輕松隨意。因此我嘗試用有趣的例子,來使讀者更舒服地學習,而不是感到無聊或被嚇到。

謝謝讀到這里——請在評論框里留下你的問題或建議,我很樂意回復你。

㈣ python sklearn邏輯回歸怎麼導出概率值

概率值:predict_proba()
類別:predict()

㈤ 如何用Python進行線性回歸以及誤差分析

如何用Python進行線性回歸以及誤差分析
如果你想要重命名,只需要按下:
CTRL-b
狀態條將會改變,這時你將可以重命名當前的窗口
一旦在一個會話中創建多個窗口,我們需要在這些窗口間移動的辦法。窗口像數組一樣組織在一起,從0開始用數字標記每個窗口,想要快速跳轉到其餘窗口:
CTRL-b 《窗口號》
如果我們給窗口起了名字,我們可以使用下面的命令找到它們:
CTRL-b f
也可以列出所有窗口:
CTRL-b w

㈥ python多元線性回歸怎麼計算

1、什麼是多元線性回歸模型?

當y值的影響因素不唯一時,採用多元線性回歸模型。

y =y=β0+β1x1+β2x2+...+βnxn

例如商品的銷售額可能不電視廣告投入,收音機廣告投入,報紙廣告投入有關系,可以有 sales =β0+β1*TV+β2* radio+β3*newspaper.

2、使用pandas來讀取數據

pandas 是一個用於數據探索、數據分析和數據處理的python庫

[python]view plain

㈦ python 線性回歸 linregress 輸出結果怎麼看

import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='roo...
答:試試這個fetchone函數 conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306) cur=conn.cursor() cur.execute('select * from user') data = cur.fetchone() print "Database : %s " % data conn.commit() cur.

㈧ 怎麼看python中邏輯回歸輸出的解釋

以下為python代碼,由於訓練數據比較少,這邊使用了批處理梯度下降法,沒有使用增量梯度下降法。

##author:lijiayan##data:2016/10/27
##name:logReg.pyfrom numpy import *import matplotlib.pyplot as pltdef loadData(filename):
data = loadtxt(filename)
m,n = data.shape print 'the number of examples:',m print 'the number of features:',n-1 x = data[:,0:n-1]
y = data[:,n-1:n] return x,y#the sigmoid functiondef sigmoid(z): return 1.0 / (1 + exp(-z))#the cost functiondef costfunction(y,h):
y = array(y)
h = array(h)
J = sum(y*log(h))+sum((1-y)*log(1-h)) return J# the batch gradient descent algrithmdef gradescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features x = c_[ones(m),x] #add x0 x = mat(x) # to matrix y = mat(y)
a = 0.0000025 # learning rate maxcycle = 4000 theta = zeros((n+1,1)) #initial theta J = [] for i in range(maxcycle):
h = sigmoid(x*theta)
theta = theta + a * (x.T)*(y-h)
cost = costfunction(y,h)
J.append(cost)

plt.plot(J)
plt.show() return theta,cost#the stochastic gradient descent (m should be large,if you want the result is good)def stocGraddescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features x = c_[ones(m),x] #add x0 x = mat(x) # to matrix y = mat(y)
a = 0.01 # learning rate theta = ones((n+1,1)) #initial theta J = [] for i in range(m):
h = sigmoid(x[i]*theta)
theta = theta + a * x[i].transpose()*(y[i]-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show() return theta,cost#plot the decision boundarydef plotbestfit(x,y,theta):
plt.plot(x[:,0:1][where(y==1)],x[:,1:2][where(y==1)],'ro')
plt.plot(x[:,0:1][where(y!=1)],x[:,1:2][where(y!=1)],'bx')
x1= arange(-4,4,0.1)
x2 =(-float(theta[0])-float(theta[1])*x1) /float(theta[2])

plt.plot(x1,x2)
plt.xlabel('x1')
plt.ylabel(('x2'))
plt.show()def classifyVector(inX,theta):
prob = sigmoid((inX*theta).sum(1)) return where(prob >= 0.5, 1, 0)def accuracy(x, y, theta):
m = shape(y)[0]
x = c_[ones(m),x]
y_p = classifyVector(x,theta)
accuracy = sum(y_p==y)/float(m) return accuracy

調用上面代碼:

from logReg import *
x,y = loadData("horseColicTraining.txt")
theta,cost = gradescent(x,y)print 'J:',cost

ac_train = accuracy(x, y, theta)print 'accuracy of the training examples:', ac_train

x_test,y_test = loadData('horseColicTest.txt')
ac_test = accuracy(x_test, y_test, theta)print 'accuracy of the test examples:', ac_test

學習速率=0.0000025,迭代次數=4000時的結果:

似然函數走勢(J = sum(y*log(h))+sum((1-y)*log(1-h))),似然函數是求最大值,一般是要穩定了才算最好。

從上面這個例子,我們可以看到對特徵進行歸一化操作的重要性。

㈨ python 嶺回歸



所求參數是alpha的函數,比如記為f(alpha),f(alpha)隨alpha的改變的軌跡就是嶺跡。
實際計算中可選非常多的alpha值,做出一個嶺跡圖,看看這個圖在取哪個值的時候變穩定了,
那就確定alpha值了,從而確定參數。

Ridge(alpha=1.0,fit_intercept=False)
model.fit(x,y)

這樣就等於你算的,因為你numpy是用增廣矩陣算的,所以應該將setfit_intercept=False
model.coef_
array([[1.06059732,0.48614918,0.44596739]])

㈩ python做邏輯回歸 怎麼把導入的數據分成x,y

簡介
本例子是通過對一組邏輯回歸映射進行輸出,使得網路的權重和偏置達到最理想狀態,最後再進行預測。其中,使用GD演算法對參數進行更新,損耗函數採取交叉商來表示,一共訓練10000次。
2.python代碼
#!/usr/bin/python

import numpy
import theano
import theano.tensor as T
rng=numpy.random

N=400
feats=784
# D[0]:generate rand numbers of size N,element between (0,1)
# D[1]:generate rand int number of size N,0 or 1
D=(rng.randn(N,feats),rng.randint(size=N,low=0,high=2))
training_steps=10000

# declare symbolic variables
x=T.matrix('x')
y=T.vector('y')
w=theano.shared(rng.randn(feats),name='w') # w is shared for every input
b=theano.shared(0.,name='b') # b is shared too.

print('Initial model:')
print(w.get_value())
print(b.get_value())

# construct theano expressions,symbolic
p_1=1/(1+T.exp(-T.dot(x,w)-b)) # sigmoid function,probability of target being 1
prediction=p_1>0.5
xent=-y*T.log(p_1)-(1-y)*T.log(1-p_1) # cross entropy
cost=xent.mean()+0.01*(w**2).sum() # cost function to update parameters
gw,gb=T.grad(cost,[w,b]) # stochastic gradient descending algorithm

#compile
train=theano.function(inputs=[x,y],outputs=[prediction,xent],updates=((w,w-0.1*gw),(b,b-0.1*gb)))
predict=theano.function(inputs=[x],outputs=prediction)

# train
for i in range(training_steps):
pred,err=train(D[0],D[1])

print('Final model:')
print(w.get_value())
print(b.get_value())
print('target values for D:')
print(D[1])
print('prediction on D:')
print(predict(D[0]))

print('newly generated data for test:')
test_input=rng.randn(30,feats)
print('result:')
print(predict(test_input))

3.程序解讀
如上面所示,首先導入所需的庫,theano是一個用於科學計算的庫。然後這里我們隨機產生一個輸入矩陣,大小為400*784的隨機數,隨機產生一個輸出向量大小為400,輸出向量為二值的。因此,稱為邏輯回歸。
然後初始化權重和偏置,它們均為共享變數(shared),其中權重初始化為較小的數,偏置初始化為0,並且列印它們。
這里我們只構建一層網路結構,使用的激活函數為logistic sigmoid function,對輸入量乘以權重並考慮偏置以後就可以算出輸入的激活值,該值在(0,1)之間,以0.5為界限進行二值化,然後算出交叉商和損耗函數,其中交叉商是代表了我們的激活值與實際理論值的偏離程度。接著我們使用cost分別對w,b進行求解偏導,以上均為符號表達式運算。
接著我們使用theano.function進行編譯優化,提高計算效率。得到train函數和predict函數,分別進行訓練和預測。
接著,我們對數據進行10000次的訓練,每次訓練都會按照GD演算法進行更新參數,最後我們得到了想要的模型,產生一組新的輸入,即可進行預測。

閱讀全文

與python回歸結果輸出相關的資料

熱點內容
中國移動長沙dns伺服器地址 瀏覽:249
wifi密碼加密了怎麼破解嗎 瀏覽:596
linux命令cpu使用率 瀏覽:67
linux實用命令 瀏覽:238
傳奇引擎修改在線時間命令 瀏覽:109
php取域名中間 瀏覽:897
cad命令欄太小 瀏覽:830
php開發環境搭建eclipse 瀏覽:480
qt文件夾名稱大全 瀏覽:212
金山雲伺服器架構 瀏覽:230
安卓系統筆記本怎麼切換系統 瀏覽:618
u盤加密快2個小時還沒有搞完 瀏覽:93
小米有品商家版app叫什麼 瀏覽:94
行命令調用 瀏覽:436
菜鳥裹裹員用什麼app 瀏覽:273
窮查理寶典pdf下載 瀏覽:514
csgo您已被禁用此伺服器怎麼辦 瀏覽:398
打開加密軟體的方法 瀏覽:156
雲存儲伺服器可靠嗎 瀏覽:967
2核1g的雲伺服器能帶動游戲嘛 瀏覽:898