用TensorFlow根據三十四所複試線線性迴歸預測工科考研國家線

數據爲三十四所近四年分數線,結果預測277,由此推斷爲275或者280


#coding=utf-8

import tensorflow as tf
import numpy as np

#導入數據,數據
my_matrix = np.loadtxt(open("inputdata.csv","rb"),delimiter=",",skiprows=0)
l1 = my_matrix[:,1]
l2 = my_matrix[:,2]
l3 = my_matrix[:,3]
l4 = my_matrix[:,4]
# 定義模型參數
W2 = tf.Variable([0.4], tf.float32)
W3 = tf.Variable([0.15], tf.float32)
W4 = tf.Variable([0.44], tf.float32)
b = tf.Variable([0.0], tf.float32)
# 定義模型
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)
x4 = tf.placeholder(tf.float32)
linear_model = W2*x2   + W3*x3   + W4*x4 + b  #三元迴歸
y = tf.placeholder(tf.float32)
# 設置損失函數
loss = tf.reduce_sum(tf.square(linear_model - y)/100) # sum of the squares
# 設置優化方法
optimizer = tf.train.GradientDescentOptimizer(0.00001)#梯度下降
train = optimizer.minimize(loss)#最小化損失函數 損失函數可以試試其他的
# 輸入訓練數據
x2_train=l2.tolist()
x3_train=l3.tolist()
x4_train=l4.tolist()
y_train=l1.tolist()
# 初始化
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# 循環訓練
for i in range(1000000):
  sess.run(train,{x2:x2_train, x3:x3_train, x4:x4_train, y:y_train})
  if(i%1000==0):
    print(sess.run([W2, W3, W4, b]),{x2:x2_train, x3:x3_train, x4:x4_train, y:y_train})
    curr_W2, curr_W3, curr_W4, curr_b, curr_loss = sess.run([W2, W3, W4, b, loss],{x2: x2_train, x3: x3_train, x4: x4_train, y: y_train})
    print("%d score:%d"%(i,curr_W2 * 265 + curr_W3 * 280 + curr_W4 * 285 + b))

print("%d W2: %s W3: %s W4: %s b: %s loss: %s" % (W2, W2, W2, b, loss))
print(sess.run(loss,{x2:x2_train,x3:x3_train,x4:x4_train, y:y_train}))

# 輸出
curr_W2, curr_W3, curr_W4, curr_b, curr_loss  = sess.run([W2, W3, W4, b, loss], {x2:x2_train,x3:x3_train,x4:x4_train, y:y_train})
print("W2: %s W3: %s W4: %s b: %s loss: %s"%(curr_W2, curr_W3, curr_W4, curr_b, curr_loss))
print(curr_W2*265+curr_W3*280+curr_W4*285 + b)

訓練結果

數據爲(可用excel保存,格式爲csv)

1,320,310,320,320
2,300,315,315,310
3,300,300,300,300
4,320,315,320,310
5,330,310,320,320
6,325,325,330,330
7,330,330,335,330
8,320,295,310,310
9,330,310,325,330
10,325,315,325,325
11,320,310,310,310
12,285,280,280,280
13,330,300,300,300
14,320,315,315,315
15,300,300,305,305
16,315,310,315,315
17,310,310,320,330
18,300,320,310,310
19,310,310,310,315
20,305,295,300,305
21,320,320,325,310
22,320,320,340,325
23,330,320,320,330
24,310,300,290,300
25,300,315,325,325
26,310,310,320,320
27,320,320,325,330
28,340,320,335,330
29,320,320,320,320
30,290,290,300,300
31,330,320,320,315
32,320,310,320,315
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章