smo_counts = dict(Counter(smo_y))
时间: 2024-03-24 13:38:18 浏览: 23
这段代码是用来统计列表 smo_y 中各元素出现的次数,并将结果存储在字典 smo_counts 中。具体来说,Counter(smo_y) 创建了一个 Counter 对象,该对象可以统计 smo_y 中各元素出现的次数,然后将结果存储在一个字典中。最后,dict() 函数将 Counter 对象转换为字典类型。这样,smo_counts 就成为了一个字典,其中每个键表示 smo_y 中的一个元素,对应的值表示该元素在 smo_y 中出现的次数。
相关问题
python svm算法smo cifar_使用smo算法编写svm对CIFAR-10数据分类
SVM算法通过将数据映射到高维空间,将数据分为两个类别。SVM算法的目标是找到一个超平面,可以将数据分为两个类别。SMO算法是一种优化算法,用于求解SVM中的二次规划问题。下面介绍如何使用SMO算法编写SVM对CIFAR-10数据进行分类。
首先,我们需要加载CIFAR-10数据集。CIFAR-10数据集包含10个类别的60000个32x32彩色图像。每个类别包含6000个图像。我们将使用Python中的pickle模块来加载数据集。以下是加载数据集的代码:
```python
import pickle
import numpy as np
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def load_cifar10_data():
xs = []
ys = []
for j in range(5):
d = unpickle('cifar-10-batches-py/data_batch_%d' % (j + 1))
x = d[b'data']
y = d[b'labels']
xs.append(x)
ys.append(y)
d = unpickle('cifar-10-batches-py/test_batch')
xs.append(d[b'data'])
ys.append(d[b'labels'])
x = np.concatenate(xs) / np.float32(255)
y = np.concatenate(ys)
return x.reshape((len(x), -1)), np.array(y)
```
接下来,我们将使用SMO算法来训练SVM模型。以下是使用SMO算法训练SVM模型的代码:
```python
class SVM:
def __init__(self, C, toler, kernel_opt=('linear', 0)):
self.C = C
self.toler = toler
self.kernel_opt = kernel_opt
def fit(self, X, y):
n_samples, n_features = X.shape
alpha = np.zeros(n_samples)
b = 0
kernel = kernel_set[self.kernel_opt[0]]
K = np.zeros((n_samples, n_samples))
for i in range(n_samples):
K[:, i] = kernel(X, X[i], self.kernel_opt[1])
iter = 0
while iter < max_iter:
num_changed_alphas = 0
for i in range(n_samples):
Ei = np.dot(alpha * y, K[:, i]) + b - y[i]
if (y[i] * Ei < -self.toler and alpha[i] < self.C) or \
(y[i] * Ei > self.toler and alpha[i] > 0):
j = np.random.choice([x for x in range(n_samples) if x != i])
Ej = np.dot(alpha * y, K[:, j]) + b - y[j]
alpha_i_old, alpha_j_old = alpha[i], alpha[j]
if y[i] != y[j]:
L = max(0, alpha[j] - alpha[i])
H = min(self.C, self.C + alpha[j] - alpha[i])
else:
L = max(0, alpha[i] + alpha[j] - self.C)
H = min(self.C, alpha[i] + alpha[j])
if L == H:
continue
eta = 2.0 * K[i, j] - K[i, i] - K[j, j]
if eta >= 0:
continue
alpha[j] -= y[j] * (Ei - Ej) / eta
alpha[j] = min(alpha[j], H)
alpha[j] = max(alpha[j], L)
if abs(alpha[j] - alpha_j_old) < 1e-5:
continue
alpha[i] += y[i] * y[j] * (alpha_j_old - alpha[j])
b1 = b - Ei - y[i] * (alpha[i] - alpha_i_old) * K[i, i] - \
y[j] * (alpha[j] - alpha_j_old) * K[i, j]
b2 = b - Ej - y[i] * (alpha[i] - alpha_i_old) * K[i, j] - \
y[j] * (alpha[j] - alpha_j_old) * K[j, j]
if 0 < alpha[i] < self.C:
b = b1
elif 0 < alpha[j] < self.C:
b = b2
else:
b = (b1 + b2) / 2
num_changed_alphas += 1
if num_changed_alphas == 0:
iter += 1
else:
iter = 0
self.X = X
self.y = y
self.kernel = kernel
self.alpha = alpha
self.b = b
def predict(self, X):
n_samples, n_features = X.shape
K = np.zeros((n_samples, len(self.X)))
for i in range(n_samples):
K[i, :] = self.kernel(self.X, X[i], self.kernel_opt[1])
y_pred = np.dot(self.alpha * self.y, K) + self.b
return np.sign(y_pred)
```
最后,我们使用以下代码来加载数据集并使用SMO算法训练SVM模型:
```python
X, y = load_cifar10_data()
y[y == 0] = -1
X_train, X_test = X[:50000], X[50000:]
y_train, y_test = y[:50000], y[50000:]
svm = SVM(C=1.0, toler=0.001, kernel_opt=('rbf', 1))
svm.fit(X_train, y_train)
y_pred_train = svm.predict(X_train)
y_pred_test = svm.predict(X_test)
train_acc = np.mean(y_train == y_pred_train)
test_acc = np.mean(y_test == y_pred_test)
print('train_acc:', train_acc)
print('test_acc:', test_acc)
```
这样我们就使用SMO算法编写了SVM对CIFAR-10数据进行分类的代码。
在PMSM中的SMO+PLL代码
以下是一个基于STM32的PMSM电机控制器中,使用了基于滑模观察器(SMO)和锁相环(PLL)的代码示例:
```
#include "stm32f4xx.h"
#include "arm_math.h"
#define PI 3.14159265358979323846f
#define SQRT3 1.73205080756887729352f
// Motor parameters (需要根据具体电机的参数进行修改)
#define R_PHASE 0.83f
#define L_D 0.000354f
#define L_Q 0.000354f
#define POLE_PAIRS 7
// SMO parameters
#define SMO_LAMBDA 10.0f
#define SMO_BETA 1.0f
// PLL parameters
#define PLL_KP 0.5f
#define PLL_KI 0.01f
// Sampling frequency
#define FS 10000.0f
// Global variables
float32_t V_alpha, V_beta, V_d, V_q, I_alpha, I_beta, I_d, I_q, theta_elec, theta_mech;
float32_t Id_error, Iq_error, Id_ref, Iq_ref, Id_out, Iq_out, Vd_out, Vq_out;
float32_t smo_estimated_flux_d, smo_estimated_flux_q, smo_estimated_speed;
float32_t pll_estimated_speed, pll_error, pll_integral, pll_proportional;
float32_t sector_angle, sector_duty_cycle, period_ticks, pwm_ticks;
float32_t sin_theta, cos_theta, sin_theta_120, cos_theta_120, sin_theta_240, cos_theta_240;
// Sine and cosine lookup tables
const float32_t sin_table[360] = {...};
const float32_t cos_table[360] = {...};
// SMO function
void SMO(float32_t V_alpha, float32_t V_beta, float32_t I_alpha, float32_t I_beta, float32_t dt)
{
float32_t Lm, Ls, Rs, inv_Ls, sm_alpha, sm_beta, sm_d, sm_q, sm_flux_norm;
float32_t smo_error_d, smo_error_q, smo_error_norm, smo_psi_alpha, smo_psi_beta;
Lm = L_D + L_Q + (R_PHASE * dt) / 2.0f;
Ls = L_D + L_Q - (R_PHASE * dt) / 2.0f;
Rs = R_PHASE;
inv_Ls = 1.0f / Ls;
// Clarke transform
sm_alpha = I_alpha;
sm_beta = SQRT3 * I_beta - SQRT3 / 2.0f * I_alpha;
// Park transform
sm_d = cos_theta * sm_alpha + sin_theta * sm_beta;
sm_q = -sin_theta * sm_alpha + cos_theta * sm_beta;
// Compute estimated flux
smo_estimated_flux_d += dt * (-smo_estimated_flux_d * SMO_LAMBDA / Lm + sm_d);
smo_estimated_flux_q += dt * (-smo_estimated_flux_q * SMO_LAMBDA / Lm + sm_q);
sm_flux_norm = arm_sqrt_f32(smo_estimated_flux_d * smo_estimated_flux_d + smo_estimated_flux_q * smo_estimated_flux_q);
// Compute error between estimated and actual flux
smo_psi_alpha = Lm * Id_out + smo_estimated_flux_d;
smo_psi_beta = Lm * Iq_out + smo_estimated_flux_q;
smo_error_d = sm_d - (smo_psi_alpha * cos_theta + smo_psi_beta * sin_theta) * inv_Ls;
smo_error_q = sm_q - (-smo_psi_alpha * sin_theta + smo_psi_beta * cos_theta) * inv_Ls;
smo_error_norm = arm_sqrt_f32(smo_error_d * smo_error_d + smo_error_q * smo_error_q);
// Update estimated speed
smo_estimated_speed = (smo_estimated_flux_q * smo_error_d - smo_estimated_flux_d * smo_error_q) / (sm_flux_norm * sm_flux_norm + SMO_BETA);
// Compute d and q current estimates
Id_out = smo_psi_alpha * inv_Ls + smo_estimated_speed * smo_estimated_flux_q / sm_flux_norm;
Iq_out = smo_psi_beta * inv_Ls - smo_estimated_speed * smo_estimated_flux_d / sm_flux_norm;
}
// PLL function
void PLL(float32_t V_alpha, float32_t V_beta, float32_t I_alpha, float32_t I_beta, float32_t dt)
{
float32_t V_d_filtered, V_q_filtered, I_d_filtered, I_q_filtered, V_cross, I_cross;
// Clarke transform
I_alpha = I_alpha;
I_beta = SQRT3 * I_beta - SQRT3 / 2.0f * I_alpha;
// Park transform
I_d = cos_theta * I_alpha + sin_theta * I_beta;
I_q = -sin_theta * I_alpha + cos_theta * I_beta;
// Compute Vd and Vq
V_d = V_alpha - Rs * I_d - smo_estimated_speed * smo_estimated_flux_q;
V_q = V_beta - Rs * I_q + smo_estimated_speed * smo_estimated_flux_d;
// Low-pass filter Vd and Vq
V_d_filtered += dt * (V_d - V_d_filtered) / (L_D * 2.0f * PI * 1000.0f + dt);
V_q_filtered += dt * (V_q - V_q_filtered) / (L_Q * 2.0f * PI * 1000.0f + dt);
// Low-pass filter Id and Iq
I_d_filtered += dt * (I_d - I_d_filtered) / (L_D * 2.0f * PI * 1000.0f + dt);
I_q_filtered += dt * (I_q - I_q_filtered) / (L_Q * 2.0f * PI * 1000.0f + dt);
// Compute V and I cross products
V_cross = V_d_filtered * I_q_filtered - V_q_filtered * I_d_filtered;
I_cross = I_d_filtered * smo_estimated_flux_q - I_q_filtered * smo_estimated_flux_d;
// Compute estimated speed
pll_error = V_cross / (V_cross * V_cross + I_cross * I_cross);
pll_integral += pll_error * dt;
pll_proportional = pll_error * PLL_KP;
pll_estimated_speed = pll_proportional + pll_integral * PLL_KI;
}
// PWM function
void PWM(float32_t duty_cycle)
{
if (duty_cycle < 0.0f) {
duty_cycle = 0.0f;
} else if (duty_cycle > 1.0f) {
duty_cycle = 1.0f;
}
if (duty_cycle > 0.0f) {
TIM1->CCR1 = (uint16_t)(duty_cycle * pwm_ticks);
TIM1->CCR2 = (uint16_t)(duty_cycle * pwm_ticks);
TIM1->CCR3 = (uint16_t)(duty_cycle * pwm_ticks);
} else {
TIM1->CCR1 = 0;
TIM1->CCR2 = 0;
TIM1->CCR3 = 0;
}
}
// Main function
int main(void)
{
// Initialize GPIO pins, timers, ADC, etc.
// Main loop
while (1) {
// Read ADC values and convert to currents and voltages
V_alpha = ...;
V_beta = ...;
I_alpha = ...;
I_beta = ...;
// Compute electrical and mechanical angles
theta_elec += 2.0f * PI * (pll_estimated_speed / (POLE_PAIRS * FS));
if (theta_elec >= 2.0f * PI) {
theta_elec -= 2.0f * PI;
}
theta_mech = theta_elec / POLE_PAIRS;
// Compute sector angle and duty cycle
sector_angle = theta_mech / (2.0f * PI / 3.0f);
if (sector_angle < 0.0f) {
sector_angle += 3.0f;
}
if (sector_angle >= 3.0f) {
sector_angle -= 3.0f;
}
if (sector_angle < 1.0f) {
sector_duty_cycle = sin_theta / 2.0f + cos_theta / SQRT3 * sin_theta_120 / 2.0f;
} else if (sector_angle < 2.0f) {
sector_duty_cycle = cos_theta / SQRT3 * sin_theta_120 / 2.0f - sin_theta / 2.0f;
} else {
sector_duty_cycle = -cos_theta / SQRT3 * sin_theta_120 / 2.0f - cos_theta / 2.0f;
}
// Compute period and PWM ticks
period_ticks = (uint32_t)(SystemCoreClock / (POLE_PAIRS * FS));
pwm_ticks = (uint32_t)(period_ticks * sector_duty_cycle);
// Run SMO and PLL
SMO(V_alpha, V_beta, I_alpha, I_beta, 1.0f / FS);
PLL(V_alpha, V_beta, I_alpha, I_beta, 1.0f / FS);
// Compute Id and Iq references
Id_error = Id_ref - Id_out;
Iq_error = Iq_ref - Iq_out;
// Run PI controllers for Id and Iq
Vd_out = Id_error * L_D * 2.0f * PI * 1000.0f + Iq_error * smo_estimated_speed * L_Q * 2.0f * PI * 1000.0f;
Vq_out = Iq_error * L_Q * 2.0f * PI * 1000.0f - Id_error * smo_estimated_speed * L_D * 2.0f * PI * 1000.0f;
// Run PWM
PWM(sector_duty_cycle);
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)