簡體   English   中英

使用Scikit-Learn學習乘法

[英]Learn to multiply using Scikit-Learn

我編寫了一個學習添加的程序,

from sklearn import linear_model
from random import randint
reg=linear_model.LinearRegression()
x=[[randint(0,100),randint(0,100)] for i in range(1000)]
Y=[i[0]+i[1] for i in x]
reg.fit(x, Y)
print(reg.pred([[56, 23]])
# OUTPUT : 79

如果我想讓它做乘法,請幫助我解決這個程序,我的精度很低。

由於我是新手,請對程序進行盡可能少的更改。

!!提前致謝!!

好吧,您有多種解決方案。
要實現0錯誤,您需要學習一個可以學習這種復雜性的模型。 您可能希望使用線性回歸之類的簡單模型,因此,應使用多項式特征擴展數據。 sklearn.processing.PolynomialFeatures 這里

替代解決方案可能涉及更復雜的模型,例如神經網絡 您可以簡單地使用具有2-3個隱藏層的多層網絡以及線性輸出層,以使輸出不受限制。 這種方法將不太適合此類問題,因為它比較復雜,並且不能保證在您的問題上表現最佳。

注意事項
如果您確實選擇嘗試解決此簡單問題的網絡,請確保使用平均損失

范例

首先,讓我們加載一些工具。
我們將使用線性回歸和scikit-learn的預處理工具包。

from sklearn import linear_model
from sklearn import preprocessing
from random import randint
import numpy as np

加法問題

# Lets generate some random data
x=[[randint(0,100),randint(0,100)] for i in range(1000)]

# and compute the deterministic addition function
Y=[i[0]+i[1] for i in x]

由於x+yxy的線性組合,因此我們不需要對數據進行任何特征提取。 線性回歸中的最小化目標為np.sum((x * w -Y) ** 2) ,其中我們對w進行最小化。 該模型的最佳參數為[1, 1]

# First, we create an instance of the regressor
reg_add=linear_model.LinearRegression()

# then, fit it to the data
reg_add.fit(x, Y)

# and finally, test it on some sample
sample = [[56, 23]]
print('Addition: X={}, Y_hat={}'.format(sample,reg_add.predict(sample)))

輸出:

Addition: X=[[56, 23]], Y_hat=[79.]

乘法問題

# Again, lets generate some random data
x=[[randint(0,100),randint(0,100)] for i in range(1000)]

# And compute the multiplication of all coordinates for each sample
Y=np.array([i[0]*i[1] for i in x])

現在,由於x[0]*x[1] 不是樣本中元素的線性組合,因此簡單的線性回歸無法准確擬合數據。 但是,如果選擇多項式特征提取,則可以。 多項式特征是指直到指定次數(包括次數0的坐標的所有多項式組合。

# Lets create an instance of the processor, using polynomial features of degree=2
pp = preprocessing.PolynomialFeatures(2)

# transform the original data
x2 = pp.fit_transform(x)

# Then, create a linear regressor,
reg_mult=linear_model.LinearRegression()

# Fit it to the processed data and the results
reg_mult.fit(x2, Y)

# and test it on a new example.
sample = [[2, 4]]
print('Multiplication: X={}, Y_hat={}'.format(sample,reg_mult.predict(pp.transform(sample))))

輸出:

Multiplication: X=[[2, 4]], Y_hat=[8.]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM