### 代码概述

```#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
double w, q;
int m;
//模型
float Model(float x)
{
float y;
y = x * w + q;
return y;
}
//损失函数
double Loss(float *y,float *x)
{
double L=0;
//循环参数
int i, j, k;
for (i = 0; i < m; i++)
{
L += (pow((y[i] - Model(x[i])), 2)) / (2 * m);
}
return L;
}
//梯度下降优化函数
{
int j, i;
double Q = 0, W = 0;
for (i = 0; i < m; i++)
W += x[i] * (Model(x[i]) - y[i]);
W = W / m;
for (j = 0; j < m; j++)
Q += Model(x[j]) - y[j];
Q = Q / m;
printf("W:%f
Q:%f
", W, Q);
w = w - a * W;
q = q - a * Q;
}
//主函数;训练过程
int main()
{
//循环标志
int i, j;
//训练轮次
int epoch;
//损失函数
double L;
//学习率
float a;
float x[100], y[100];
//随机数生成
for (i = 0; i < 100; i++)
{
x[i] = 0.1*i;
y[i] = x[i] * 3 + 5; //+ ((rand() % 11) / 10);
printf("X:%.2f,Y:%.2f
", x[i], y[i]);
}
//超参数设置
m = 100;
a = 0.05;
epoch = 1000;
//参数初始化
w = 2;
q = 3;
for (j = 0; j < epoch; j++)
{
L = Loss(y, x);
printf("训练轮次:%d,损失:%f,参数w的值:%lf,参数q的值:%lf
", j+1, L, w, q);
}
printf("最终值:
w:%lf
q:%lf
", w, q);
system("pause");
}```

1.参数更新

2.保留损失函数

3.注意数据类型

4.超参数的设置及参数的初始化

### 心得

```# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
np.random.seed(5)
x_data = np.linspace(-1,1,100)
y_data = 2 * x_data + 1.0 + np.random.randn(*x_data.shape) * 0.4
np.random.randn(10)
#x_data.shape
#np.random.randn(*x_data.shape)
#np.random.randn(100)
plt.scatter(x_data,y_data)
plt.plot(x_data, 2 * x_data + 1.0, color = 'red',linewidth=3)
x = tf.placeholder("float",name="x")
y = tf.placeholder("float",name="y")
def model(x,w,b):
return tf.multiply(x,w)+b
w = tf.Variable(1.0,name="w0")
b = tf.Variable(0.0,name="b0")
pred = model(x,w,b)
train_epochs = 10
learning_rate = 0.05
loss_function = tf.reduce_mean(tf.square(y-pred))
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
i_ci=0
for epoch in range(train_epochs):
for xs,ys in zip(x_data,y_data):
_, loss=sess.run([optimizer,loss_function],feed_dict={x:xs,y:ys})
b0temp=b.eval(session=sess)
w0temp=w.eval(session=sess)
plt.plot(x_data,w0temp*x_data+b0temp)

print("w:",sess.run(w))
print("b:",sess.run(b))
plt.scatter(x_data,y_data,label='Original data')
plt.plot(x_data,x_data*sess.run(w)+sess.run(b),label='Fitted Line',color='r',linewidth=3)
plt.legend(loc=2)```